Intervals (LeetCode #16)
Interval problems are almost all the same move: sort, then sweep. The decisions are which end to sort by and what to track during the sweep. This post covers all 6 NeetCode Intervals problems.
The technique
Sort by start for merging and overlap checks (an overlap can only involve the interval being built). Sort by end for scheduling (earliest finish leaves the most room). Sweep two sorted lists (starts and ends) for counting overlaps.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
a/.style={->, thick, black!45}]
\draw[a] (0,0) -- (7.2,0) node[below, font=\small] {time};
\fill[blue!20] (0.3,0.2) rectangle (2.0,0.5); \node[font=\scriptsize] at (1.15,0.35) {[1,3]};
\fill[orange!25] (1.6,0.8) rectangle (3.6,1.1); \node[font=\scriptsize] at (2.6,0.95) {[2,6]};
\fill[green!28] (0.3,1.5) rectangle (3.6,1.8); \node[font=\scriptsize] at (1.95,1.65) {[1,6] merged};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (3.6,-0.5) {sort by start, then extend when the next start overlaps};
\end{tikzpicture}
Insert Interval
The question. Insert newInterval into a sorted, non-overlapping list and merge.
Input: intervals = [[1,3],[6,9]], new = [2,5] -> [[1,5],[6,9]]
The idea. Three phases: copy intervals ending before the new start; absorb all overlapping intervals (min start, max end); append the merged interval, then the rest.
Walk it through on intervals = [[1,3],[6,9]], new = [2,5]:
| phase | check | action |
|---|---|---|
| copy | [1,3]: end 3 < 2? no |
nothing copied |
| absorb | [1,3]: start 1 ≤ 5 → merge → [1,5] |
[6,9]: start 6 ≤ 5? no → stop |
| finish | append [1,5], extend [[6,9]] |
[[1,5],[6,9]] |
def insert(intervals, new):
out, i, n = [], 0, len(intervals)
while i < n and intervals[i][1] < new[0]:
out.append(intervals[i]); i += 1 # strictly before
while i < n and intervals[i][0] <= new[1]:
new[0] = min(new[0], intervals[i][0]) # absorb
new[1] = max(new[1], intervals[i][1])
i += 1
out.append(new)
out.extend(intervals[i:])
return out
Why the two comparisons differ. end < new[0] (strict) selects intervals fully left; start <= new[1] admits touching intervals into the merge. Touching [1,2] and [2,3] counts as overlapping here, which the asymmetry encodes.
Complexity. \(O(n)\) time, \(O(n)\) output space.
Edge cases. Empty list → [new]. new swallowed entirely by an existing interval is returned unchanged. Mutating the input new list in place is fine for the problem but worth noting.
Merge Intervals
The question. Merge all overlapping intervals.
Input: [[1,3],[2,6],[8,10],[15,18]] -> [[1,6],[8,10],[15,18]]
The idea. Sort by start. For each interval, if its start ≤ the last merged end, extend that end (with max); otherwise start a new group.
Walk it through on [[1,3],[2,6],[8,10],[15,18]] (already sorted):
\begin{tikzpicture}[font=\rmfamily, >=stealth]
\draw[thick, fill=blue!15] (0.5,0.9) rectangle (1.5,1.15);
\draw[thick, fill=blue!15] (1.0,0.55) rectangle (3.0,0.8);
\draw[thick, fill=green!15] (4.0,0.9) rectangle (5.0,1.15);
\draw[thick, fill=green!15] (7.5,0.55) rectangle (9.0,0.8);
\node[font=\scriptsize\ttfamily, anchor=east] at (0.3,1.02) {[1,3]};
\node[font=\scriptsize\ttfamily, anchor=east] at (0.8,0.67) {[2,6]};
\draw[very thick, orange!80!black, <->] (0.5,0.35) -- (3.0,0.35);
\node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=north] at (1.75,0.3) {overlap -> [1,6]};
\end{tikzpicture}
| interval | start ≤ last end? |
merged list |
|---|---|---|
[1,3] |
first — seed | [[1,3]] |
[2,6] |
2 ≤ 3 → extend to 6 | [[1,6]] |
[8,10] |
8 > 6 → new group | [[1,6],[8,10]] |
[15,18] |
15 > 10 → new group | [[1,6],[8,10],[15,18]] |
def merge(intervals):
intervals.sort(key=lambda x: x[0])
out = [intervals[0]]
for start, end in intervals[1:]:
if start <= out[-1][1]:
out[-1][1] = max(out[-1][1], end)
else:
out.append([start, end])
return out
Why max and not just end. A contained interval like [2,3] inside [1,6] must not shrink the merged end; max keeps it. Sorting by start guarantees the current interval cannot extend leftward past the group, so only the end needs fixing.
Complexity. \(O(n \log n)\) time (the sort), \(O(n)\) output space (or \(O(\log n)\) stack for the sort).
Edge cases. Empty input needs a guard before taking intervals[0] (the problem guarantees non-empty). Single interval → returned as is.
Non-overlapping Intervals
The question. Remove the fewest intervals so the rest do not overlap.
The idea. Keep the most non-overlapping intervals by sorting by end and greedily keeping each interval whose start ≥ the last kept end. Answer = total − kept.
def erase_overlap(intervals):
intervals.sort(key=lambda x: x[1])
kept, last_end = 0, float("-inf")
for start, end in intervals:
if start >= last_end:
kept += 1; last_end = end
return len(intervals) - kept
\(O(n \log n)\).
Meeting Rooms
The question. Can one person attend all meetings?
Input: [[0,30],[5,10],[15,20]] -> False
The idea. Sort by start; if any meeting starts before the previous one ends, they overlap.
def can_attend(intervals):
intervals.sort(key=lambda x: x[0])
for i in range(1, len(intervals)):
if intervals[i][0] < intervals[i-1][1]:
return False
return True
\(O(n \log n)\).
Meeting Rooms II
The question. Return the minimum number of rooms needed to hold all meetings.
Input: [[0,30],[5,10],[15,20]] -> 2
The idea — sweep starts and ends. Sort all start times and all end times separately. Walk with two pointers: at each step, if the next event is a start (start < end), a new room is needed; otherwise a meeting ends and a room frees. The maximum simultaneous rooms is the answer.
Walk it through on [[0,30],[5,10],[15,20]]: starts [0,5,15], ends [10,20,30].
- start 0 < end 10 → rooms 1
- start 5 < end 10 → rooms 2 (peak)
- start 15 > end 10 → rooms 1 (freed)
- start 15 < end 20 → rooms 2
Peak 2 → 2 rooms.
def min_meeting_rooms(intervals):
starts = sorted(s for s, _ in intervals)
ends = sorted(e for _, e in intervals)
rooms = best = i = j = 0
while i < len(starts):
if starts[i] < ends[j]:
rooms += 1; best = max(best, rooms); i += 1
else:
rooms -= 1; j += 1
return best
Why the sweep works. At any moment the number of active meetings is the number of starts seen minus the number of ends seen; the maximum over time is the rooms needed.
\(O(n \log n)\) time, \(O(n)\) space. A min-heap of end times gives the same result.
Minimum Interval to Include Each Query
The question. For each query point, find the length of the smallest interval containing it, or -1.
The idea. Sort intervals by start and process queries in increasing order with a min-heap keyed by interval length. For each query q: push every interval whose start ≤ q; pop any whose end < q; the heap top is the smallest containing interval.
Walk it through on intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]:
| query | push (start ≤ q) | pop (end < q) | top | answer |
|---|---|---|---|---|
| 2 | [1,4] (len 4), [2,4] (len 3) |
none | 3 | 3 |
| 3 | [3,6] (len 4) |
none | 3 | 3 |
| 4 | [4,4] (len 1) |
none (ends are 4,4,6,4) | 1 | 1 |
| 5 | all pushed already | ends 4,4,4 gone | 4 ([3,6]) |
4 |
import heapq
def min_interval(intervals, queries):
intervals.sort()
order = sorted(range(len(queries)), key=lambda i: queries[i])
heap, res, j = [], [0] * len(queries), 0
for qi in order:
q = queries[qi]
while j < len(intervals) and intervals[j][0] <= q:
s, e = intervals[j]
heapq.heappush(heap, (e - s + 1, e))
j += 1
while heap and heap[0][1] < q:
heapq.heappop(heap)
res[qi] = heap[0][0] if heap else -1
return res
Why queries in increasing order. An interval that no longer contains q (end < q) can never contain a later (larger) query either, so popping it now is permanent. Processing out of order would require re-scanning.
Why the heap stores (length, end). The top must be the shortest still-containing interval: length orders it, and end is checked on every pop. Lengths alone could not detect expiry.
Complexity. \(O((n + q) \log n)\) time (each interval is pushed and popped once), \(O(n + q)\) space.
Edge cases. A query inside nothing → -1. Empty intervals with any query → all -1.
Pitfalls
- Not sorting first. The sweep assumes order.
- Sorting by the wrong key. Merge by start; schedule by end.
- Touching intervals. Usually
[1,2]and[2,3]do not overlap (use<). - Forgetting
maxwhen extending merges. A contained interval must not shrink the end. - Meeting Rooms II comparing wrong pointers. A start before the next end opens a room; otherwise close one.
When do you sort by start versus by end? How does the minimum-rooms sweep count overlaps?
ASolution
Sort by start for merging (compare each start to the current merged end); sort by end for maximum non-overlapping scheduling. Minimum rooms sweeps sorted starts and ends: a start strictly before the next end increases the active count, an end decreases it, and the running maximum is the answer.
Next: Bit Manipulation (LeetCode #17) — arithmetic at the level of bits.