Merge overlapping intervals.
Problem
Given [[1,3],[2,6],[8,10],[15,18]], return [[1,6],[8,10],[15,18]]. Real-world variants: merging booking slots, maintenance windows, IP ranges.
Approach
Sort by start. Walk through the intervals keeping the last merged one; if the next interval starts at or before its end, extend the end (max of ends); otherwise start a new merged interval.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
class MergeIntervals {
static int[][] merge(int[][] intervals) {
if (intervals.length == 0) return new int[0][];
int[][] sorted = intervals.clone();
Arrays.sort(sorted, Comparator.comparingInt(a -> a[0]));
List<int[]> merged = new ArrayList<>();
int[] current = sorted[0].clone();
for (int i = 1; i < sorted.length; i++) {
int[] next = sorted[i];
if (next[0] <= current[1]) {
current[1] = Math.max(current[1], next[1]); // overlap: extend
} else {
merged.add(current);
current = next.clone();
}
}
merged.add(current);
return merged.toArray(new int[0][]);
}
public static void main(String[] args) {
int[][] in = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
System.out.println(Arrays.deepToString(merge(in))); // [[1, 6], [8, 10], [15, 18]]
}
}Complexity
O(n log n) for sorting plus O(n) for the scan; O(n) output space.
Follow-up questions interviewers ask
Try answering each one before you open it.
How do you insert a new interval into a sorted, non-overlapping list?
In one pass: copy intervals that end before the new one starts; merge all intervals that overlap the new one (taking the min start and max end); then copy the remaining intervals. O(n), no sort needed.
What is the minimum number of meeting rooms needed for a set of meetings?
Sort meetings by start time and keep a min-heap of end times of meetings in progress. For each meeting, if the earliest ending meeting has ended (heap.peek() <= start), reuse that room (poll); then push this meeting's end. The heap's maximum size is the answer. O(n log n).