Intervals · Pattern 2 of 3
Line sweep: count what overlaps at every moment
Turn every interval into two events, +1 at the start and −1 at the end, sort them by time and keep a running total. The largest total is the most intervals that overlap at once.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- How many rooms, platforms or groups are needed?
- Capacity over time: do passengers ever exceed the seats?
- Free time common to everyone
- Area or length covered by many overlapping shapes
The template
// most intervals overlapping at once, half-open [start, end): ends before starts at a tie
int minMeetingRooms(int[][] intervals) {
List<int[]> events = new ArrayList<>();
for (int[] iv : intervals) { events.add(new int[]{iv[0], 1}); events.add(new int[]{iv[1], -1}); }
events.sort((a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1]));
int cur = 0, best = 0;
for (int[] e : events) { cur += e[1]; best = Math.max(best, cur); }
return best;
}
// difference array: add at the start, subtract at the end, then a running sum
boolean carPooling(int[][] trips, int capacity) {
int[] diff = new int[1001]; // stops are 0..1000
for (int[] t : trips) { diff[t[1]] += t[0]; diff[t[2]] -= t[0]; }
int load = 0;
for (int d : diff) {
load += d;
if (load > capacity) return false;
}
return true;
} def min_meeting_rooms(intervals):
events = []
for s, e in intervals:
events.append((s, 1))
events.append((e, -1))
events.sort() # by time; -1 sorts before 1, so ends come first at a tie
cur = best = 0
for _, d in events:
cur += d
best = max(best, cur)
return best
def car_pooling(trips, capacity):
diff = [0] * 1001 # stops are 0..1000
for n, a, b in trips:
diff[a] += n # get on at a
diff[b] -= n # get off at b
load = 0
for d in diff:
load += d
if load > capacity:
return False
return True // most intervals overlapping at once, half-open [start, end): ends before starts at a tie
int minMeetingRooms(vector<vector<int>>& intervals) {
vector<pair<int, int>> events;
for (auto& iv : intervals) { events.push_back({iv[0], 1}); events.push_back({iv[1], -1}); }
sort(events.begin(), events.end()); // -1 sorts before 1 at the same time
int cur = 0, best = 0;
for (auto& [t, d] : events) { cur += d; best = max(best, cur); }
return best;
}
// difference array: add at the start, subtract at the end, then a running sum
bool carPooling(vector<vector<int>>& trips, int capacity) {
vector<int> diff(1001, 0); // stops are 0..1000
for (auto& t : trips) { diff[t[1]] += t[0]; diff[t[2]] -= t[0]; }
int load = 0;
for (int d : diff) {
load += d;
if (load > capacity) return false;
}
return true;
} // most intervals overlapping at once, half-open [start, end): ends before starts at a tie
function minMeetingRooms(intervals) {
const events = [];
for (const [s, e] of intervals) events.push([s, 1], [e, -1]);
events.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
let cur = 0, best = 0;
for (const [, d] of events) { cur += d; best = Math.max(best, cur); }
return best;
}
// difference array: add at the start, subtract at the end, then a running sum
function carPooling(trips, capacity) {
const diff = new Array(1001).fill(0); // stops are 0..1000
for (const [n, a, b] of trips) { diff[a] += n; diff[b] -= n; }
let load = 0;
for (const d of diff) {
load += d;
if (load > capacity) return false;
}
return true;
} The variations
-
1Most overlapping at once
Sweep the sorted events with a running count; its peak is the number of rooms, platforms or groups. Equivalently, sort starts and ends separately and walk both like a merge. Only the tie rule changes between problems.
Now you solve -
2Difference array over time
When times are small integers, skip the sort: add the load at the start index, subtract it at the end index, and a prefix sum gives the load at every moment.
Now you solve -
3Simulate with heaps
When you must know which room each meeting takes, sweep the meetings by start and keep two min-heaps: free rooms by number, busy rooms by (free time, number). Release every room that is free by the start; if none is, the meeting waits for the earliest one.
-
4Gaps in the timeline
Put everyone's intervals into one list, sort by start and merge. The gaps between merged intervals are the times when nobody is busy.
-
5Sweep in two dimensions
Sweep a vertical line across the x events of the rectangles. Between two events the covered height stays the same, so each strip adds width × covered height. Keep how many rectangles cover each y piece to know the covered height.
-
6More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Getting the tie order wrong: for half-open meetings an end at 10 frees the room for a start at 10, but for train platforms and closed groups a train leaving at 10 still blocks one arriving at 10, so starts go first.
- Sorting starts and ends as pairs of an interval instead of as separate events: the sweep only needs the times.
- Using a difference array when times go up to 10^9: sort the events (or compress the coordinates) instead.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.