Merge Intervals

Sort by start, then sweep — merge overlaps, insert intervals, find free time and count the rooms needed.

Intermediate 2 min readLesson 6 of 25

Interval problems deal with ranges [start, end]: meetings, bookings, time slots, genomic ranges, memory regions. The core insight: after sorting by start time, overlapping intervals are adjacent, so a single linear sweep handles them.

Two intervals a and b (with a.start ≤ b.start) overlap when b.start ≤ a.end.

1-32-68-109-121236891012
[1,3] and [2,6] overlap → [1,6]; [8,10] and [9,12] → [8,12].
When to use this pattern
  • The input is a list of intervals / ranges / meetings / bookings.
  • You need to merge, insert, intersect or find gaps between them.
  • "How many rooms / platforms / resources are needed at the same time?"
  • "Can one person attend all meetings?"

Merge overlapping intervals

int[][] merge(int[][] intervals) {
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
    List<int[]> out = new ArrayList<>();
    for (int[] iv : intervals) {
        if (out.isEmpty() || out.get(out.size() - 1)[1] < iv[0]) out.add(iv);   // no overlap
        else out.get(out.size() - 1)[1] = Math.max(out.get(out.size() - 1)[1], iv[1]); // extend
    }
    return out.toArray(new int[0][]);
}

O(n log n) for sorting, O(n) for the sweep. Note max(...) when extending: a later interval can be fully contained in the current one.

Insert into sorted, non-overlapping intervals

Three phases in one pass: copy intervals ending before the new one; merge every interval overlapping it; copy the rest. O(n), no sort needed.

int[][] insert(int[][] ivs, int[] nw) {
    List<int[]> out = new ArrayList<>();
    int i = 0, n = ivs.length;
    while (i < n && ivs[i][1] < nw[0]) out.add(ivs[i++]);              // before
    while (i < n && ivs[i][0] <= nw[1]) {                              // overlapping
        nw = new int[]{Math.min(nw[0], ivs[i][0]), Math.max(nw[1], ivs[i][1])};
        i++;
    }
    out.add(nw);
    while (i < n) out.add(ivs[i++]);                                   // after
    return out.toArray(new int[0][]);
}

Meeting rooms: how many at once?

Treat each start as +1 and each end as −1 and sweep events in time order — the maximum running count is the answer. Equivalently, sort starts and ends separately and walk both with two pointers, or keep a min-heap of end times of rooms in use.

int minMeetingRooms(int[][] ivs) {
    int n = ivs.length;
    int[] starts = new int[n], ends = new int[n];
    for (int i = 0; i < n; i++) { starts[i] = ivs[i][0]; ends[i] = ivs[i][1]; }
    Arrays.sort(starts);
    Arrays.sort(ends);
    int rooms = 0, best = 0;
    for (int i = 0, j = 0; i < n; i++) {
        if (starts[i] < ends[j]) rooms++;   // a meeting starts before the earliest one ends
        else j++;                            // reuse a freed room
        best = Math.max(best, rooms);
    }
    return best;
}
Practice problems
  • Meeting Roomssort; any overlap?easy
  • Merge Intervalsmedium
  • Insert Intervalmedium
  • Non-overlapping Intervalsgreedy by end timemedium
  • Interval List Intersectionstwo pointersmedium
  • Meeting Rooms IIheap of end timesmedium
  • Minimum Number of Arrows to Burst Balloonsmedium
  • Employee Free Timemerge all, then gapshard
  • My Calendar I / IITreeMap / sweep countsmedium
Key takeaways
  • Sort by start; overlapping intervals become neighbours.
  • Overlap test after sorting: next.start ≤ current.end (or < for half-open).
  • Concurrency questions = sweep line (+1/−1 events) or a min-heap of end times.
  • Maximum non-overlapping set = greedy by earliest end.