Start learning free

LESSON 550 OF 671 · INTERVALS

Merge Intervals in Java: O(n log n) with Sorting

Practice O(n log n) Read the full explanation

You get an array of intervals. Each interval is a pair [starti, endi]. It covers every point from its start to its end.

Merge the intervals that overlap. Return an array of the intervals you end up with, sorted by start.

Two intervals overlap if they share at least one point. Intervals that only touch count too. For example, [2,5] and [5,6] share the point 5. They become [2,6].

 

Example 1:

Input: intervals = [[5,8],[1,3],[7,11],[13,14]]
Output: [[1,3],[5,11],[13,14]]
Explanation: The input is not sorted.
[5,8] and [7,11] share 7 and 8.
They become [5,11].
[1,3] and [13,14] overlap no other interval.

Example 2:

Input: intervals = [[2,5],[5,6],[9,9]]
Output: [[2,6],[9,9]]
Explanation: [2,5] and [5,6] touch at 5.
That is enough to merge them.
[9,9] is a single point.
It stays on its own.

Example 3:

Input: intervals = [[3,20],[4,6],[10,12]]
Output: [[3,20]]
Explanation: [4,6] and [10,12] lie inside [3,20].
All three merge into [3,20].
It ends at 20, not at 12.

 

Constraints:

  • 1 to 100,000 intervals, in any order.
  • Each start and end is a whole number from 0 to 1,000,000.
  • No start is greater than its end.

Note:

Your algorithm should run in O(n log n) time, where n is the number of intervals.

STEP 1 OF 7
    Ctrl + Enter to check

    JAVA · INTERVALS

    Merge Intervals in Java, explained

    Problem overview

    The method merge receives an int[][] named intervals, where each int[] holds a start and an end. It merges every group of overlapping intervals and returns the intervals that remain as an int[][], sorted by start. Two intervals overlap when they share at least one point, so [1,4] and [4,5], which share the point 4, merge into [1,5].

    For [[1,3],[2,6],[8,10],[15,18]] the result is [[1, 6], [8, 10], [15, 18]]: the first two overlap and become [1,6], and the others overlap nothing. The input can be unsorted, as in [[6,8],[1,9],[2,4],[4,7]], which merges into the single interval [[1, 9]]. The statement asks for O(n log n) time.

    Approach: sort, then sweep once

    Checking every interval against every other costs O(n²), and merging can chain: [1,3] may join [2,6], and the result may then join [5,9]. Sorting by start makes the chain easy to follow. After sorting, any intervals that overlap sit next to each other, so one left-to-right pass is enough.

    The pass keeps a list of merged intervals. For each interval, compare its start with the end of the last merged one:

    • It starts after that end. It can't overlap anything so far, because the intervals arrive in order of start. It becomes a new merged interval.
    • It starts at or before that end. It overlaps the last merged interval, so extend that one: its end becomes the larger of the two ends. Keeping the larger end matters when the new interval lies completely inside, like [2,3] inside [1,10], where the end must stay 10.

    The sort takes O(n log n) and the pass takes O(n), so the sort sets the total.

    Step by step

    1. Sort intervals by start with Arrays.sort and the comparator lambda (first, second) -> first[0] - second[0]. A negative result puts first before second.
    2. Create merged, a List<int[]> backed by a new ArrayList. The number of merged intervals isn't known in advance, so it needs to grow.
    3. Loop over every int[] interval with a for-each loop. They arrive in order of start.
    4. Name the two ends: start is interval[0] and end is interval[1], so the next lines read like the idea.
    5. Decide whether this starts a new merged interval. It does if merged is empty or the last merged interval ends before start. Use <, not <=: an interval that starts exactly where the last ends touches it, and touching intervals merge. In that case add new int[]{start, end}.
    6. Otherwise extend the last merged interval. Set its end to Math.max of its current end and end.
    7. Return merged.toArray(new int[0][]). It copies the list into a new array of arrays of exactly the right size.

    The solution in Java

    class Solution {
        public int[][] merge(int[][] intervals) {
            Arrays.sort(intervals, (first, second) -> first[0] - second[0]);
            List<int[]> merged = new ArrayList<>();
            for (int[] interval : intervals) {
                int start = interval[0], end = interval[1];
                if (merged.isEmpty() || merged.get(merged.size() - 1)[1] < start) {
                    merged.add(new int[]{start, end});
                } else {
                    merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], end);
                }
            }
            return merged.toArray(new int[0][]);
        }
    }
    

    Java details worth noticing:

    • Imports. Arrays, List and ArrayList all live in java.util. Outside the lesson's editor the file needs import java.util.*;.
    • List<int[]>. A generic list can hold int[] elements because arrays are objects, but it can't be a List<int>: generics take reference types, not primitives.
    • Changing an interval in place. merged.get(merged.size() - 1) returns the actual int[] stored in the list, not a copy, so assigning to its element [1] changes the stored interval.
    • toArray(new int[0][]). The empty array tells Java the element type, int[], and the method allocates an array of the right length. It returns an int[][], which is what merge promises.
    • What gets modified. Each merged interval is created with new int[]{start, end}, and only these new arrays are ever extended, so the rows of the input are not changed by the merging. The sort does reorder the caller's intervals array in place, so after the call the input is sorted by start. A caller who needs the original order must pass a copy.
    • Subtraction in the comparator is safe because starts stay within 0 to 1,000,000. For values near the limits of int it can overflow, and Integer.compare is the safe choice.

    Complexity

    Time: O(n log n). Sorting is O(n log n). The loop touches each interval once, and ArrayList.add and get are constant time.

    Space: O(n). In the worst case, when nothing overlaps, merged holds n intervals, and the sort uses some working space as well.

    Edge cases and common mistakes

    • Touching intervals. [[1,4],[4,5]] returns [[1, 5]]. With <= in the check they would stay apart.
    • Unsorted input. Without the sort, [[6,8],[1,9],[2,4],[4,7]] would be processed in the wrong order and miss the merges. With it, the result is [[1, 9]].
    • An interval inside another. [[1,10],[2,3]] returns [[1, 10]]. Setting the end to end instead of the larger value would shrink it to 3.
    • A single interval. [[5,5]] returns [[5, 5]]. A start equal to the end is allowed.
    • Merging into a copy. The in-place update works because get returns the stored array. Copying its values into new variables and changing those leaves the list unchanged.

    Testing

    • [[1,3],[2,6],[8,10],[15,18]] gives [[1, 6], [8, 10], [15, 18]].
    • [[1,4],[4,5]] gives [[1, 5]].
    • [[6,8],[1,9],[2,4],[4,7]] gives [[1, 9]].
    • [[1,10],[2,3]] gives [[1, 10]].
    • [[5,5]] gives [[5, 5]].
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free