Merge Intervals
Sort by start, then sweep — merge overlaps, insert intervals, find free time and count the rooms needed.
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.
- 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][]);
}def merge(intervals):
intervals.sort(key=lambda iv: iv[0])
out = []
for s, e in intervals:
if not out or out[-1][1] < s:
out.append([s, e]) # no overlap
else:
out[-1][1] = max(out[-1][1], e) # extend the last one
return outfunction merge(intervals: number[][]): number[][] {
intervals.sort((a, b) => a[0] - b[0]);
const out: number[][] = [];
for (const [s, e] of intervals) {
const last = out[out.length - 1];
if (!last || last[1] < s) out.push([s, e]);
else last[1] = Math.max(last[1], e);
}
return out;
}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][]);
}def insert(ivs, new):
out, i, n = [], 0, len(ivs)
while i < n and ivs[i][1] < new[0]:
out.append(ivs[i]); i += 1
s, e = new
while i < n and ivs[i][0] <= e:
s, e = min(s, ivs[i][0]), max(e, ivs[i][1]); i += 1
out.append([s, e])
return out + ivs[i:]function insert(ivs: number[][], nw: number[]): number[][] {
const out: number[][] = [];
let i = 0;
while (i < ivs.length && ivs[i][1] < nw[0]) out.push(ivs[i++]);
let [s, e] = nw;
while (i < ivs.length && ivs[i][0] <= e) {
s = Math.min(s, ivs[i][0]); e = Math.max(e, ivs[i][1]); i++;
}
out.push([s, e]);
return out.concat(ivs.slice(i));
}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;
}import heapq
def min_meeting_rooms(ivs):
ivs.sort(key=lambda iv: iv[0])
ends = [] # min-heap of end times of busy rooms
for s, e in ivs:
if ends and ends[0] <= s:
heapq.heapreplace(ends, e) # reuse the room that frees up first
else:
heapq.heappush(ends, e)
return len(ends)function minMeetingRooms(ivs: number[][]): number {
const starts = ivs.map((v) => v[0]).sort((a, b) => a - b);
const ends = ivs.map((v) => v[1]).sort((a, b) => a - b);
let rooms = 0, best = 0;
for (let i = 0, j = 0; i < starts.length; i++) {
if (starts[i] < ends[j]) rooms++;
else j++;
best = Math.max(best, rooms);
}
return best;
}- 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
- 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.