Greedy Algorithms · Greedy Fundamentals

Interval Overlap Counting Greedy

Sweeping sorted arrival and departure times together to track how many intervals are simultaneously active, without ever comparing every pair of intervals directly.

  • 5 min read
  • 9 practice questions
  • 2 graded problems
On this page
  1. Description
  2. The approach
  3. A second flavor: events that carry weights
  4. Where you'll see it
  5. Which tool for which job?
  6. Common mistakes
  7. Check yourself
  8. Key takeaways
  9. Quick revise
  10. Practice

Description

Trains arrive and depart; how many platforms does the station need so no train waits? Meetings start and end; how many rooms? Both ask for the largest number of intervals active at the same moment - and checking every pair of intervals, or every moment, is far more work than needed.

This skill covers the event sweep that answers this in O(n log n): sort the starts and ends, walk through them, and keep the running count and its maximum. It also covers the tie rule each problem sets, weighted events with a difference array, and why the peak is always enough capacity.

We'll go from simple to more technical:

  1. The pattern: sort arrivals and departures separately and sweep, tracking the running count.
  2. A second flavor: weighted events (Car Pooling) with a difference array.
  3. Where peak concurrency shows up (requests, connections, licenses, rooms, vehicles).
  4. What breaks it: the tie rule, pairwise checks, midnight, off-by-one in difference arrays.

The approach

Java

int minPlatforms(int[] arrival, int[] departure) {
    int[] arr = arrival.clone(), dep = departure.clone();
    Arrays.sort(arr);
    Arrays.sort(dep);                                // sorted separately: only counts matter
    int active = 0, best = 0, j = 0;
    for (int i = 0; i < arr.length; i++) {
        while (j < dep.length && dep[j] < arr[i]) {  // trains gone strictly before this arrival
            active--;
            j++;
        }
        active++;
        best = Math.max(best, active);
    }
    return best;
}

Python

def min_platforms(arrival: list[int], departure: list[int]) -> int:
    arr, dep = sorted(arrival), sorted(departure)   # sorted separately: only counts matter
    active = best = j = 0
    for a in arr:
        while j < len(dep) and dep[j] < a:          # trains gone strictly before this arrival
            active -= 1
            j += 1
        active += 1
        best = max(best, active)
    return best

The count at any moment is "arrivals so far minus departures so far", so which train an event belongs to doesn't matter - arrivals and departures can be sorted independently. The tie rule is part of the problem: here a train holds its platform through its departure minute, so a train arriving at 200 can't use the platform of one departing at 200 (only departures strictly before an arrival free a platform). Arrivals [100, 200] and departures [200, 300] need 2 platforms under this rule, 1 if the platform frees instantly.

The answer is also a lower bound that's always achievable: at the busiest moment every active train needs its own platform, and assigning each arriving train any free platform never needs more than that.

A second flavor: events that carry weights

Car Pooling: trips carry passengers from from to to, and the car must never hold more than capacity. Passengers leave at to before anyone boards there. With stops in a small range, a difference array records the changes and a prefix sum replays them:

Java

boolean carPooling(int[][] trips, int capacity) {    // each trip is [passengers, from, to]
    int[] change = new int[1001];
    for (int[] t : trips) {
        change[t[1]] += t[0];                        // they board at from
        change[t[2]] -= t[0];                        // and are out of the car at to
    }
    int inCar = 0;
    for (int c : change) {
        inCar += c;
        if (inCar > capacity) return false;
    }
    return true;
}

Python

def car_pooling(trips: list[list[int]], capacity: int) -> bool:   # each trip is [passengers, from, to]
    change = [0] * 1001
    for passengers, start, end in trips:
        change[start] += passengers                 # they board at from
        change[end] -= passengers                   # and are out of the car at to
    in_car = 0
    for c in change:
        in_car += c
        if in_car > capacity:
            return False
    return True

Applying the drop-off at to itself (not to + 1) encodes "off before on": trips [2, 1, 5] and [3, 5, 7] fit in a car of 3. With large or real-valued coordinates, sort the events instead - by position, with drop-offs before pick-ups at equal positions.

Where you'll see it

Peak concurrent requests from access logs (sort start and end timestamps and sweep), the number of database connections or licenses needed at peak, meeting rooms for a day's calendar, and capacity checks for rides or shared vehicles are all event sweeps.

Which tool for which job?

You needUse
Peak overlap, any coordinatessort starts and ends, sweep
Peak overlap, small integer timesa difference array and a prefix sum
Weighted events (passengers, load)the same sweep with weights
Which room each meeting getsstart order and a min-heap of end times
Peak after each new bookinga sorted map of deltas, or a segment tree
Huge coordinates in a difference arraycompress to the sorted distinct endpoints

Common mistakes

MistakeWhat happensDo this instead
The wrong tie ruleback-to-back trains need 1 platform instead of 2, or the reversedecide whether an end at t frees room for a start at t
Checking every pairO(n^2), and still no peaksweep sorted events
Times past midnight in HHMMa 2350-0010 train departs "before" it arrivesminutes on a timeline past 24:00
An inclusive end's -1 at endthe last moment isn't countedput it at end + 1

Check yourself

Try to answer before opening each one - recalling beats re-reading.

1. Why can arrivals and departures be sorted separately?

Show answer

The number of trains present at any moment is just arrivals so far minus departures so far. Which departure belongs to which arrival doesn't change that count, so the pairing can be thrown away.

2. Arrivals [100, 200], departures [200, 300]: 1 platform or 2?

Show answer

It depends on the tie rule. In Minimum Platforms a train holds its platform through its departure time, so the second train arrives while the first is still there - 2 platforms. If a platform freed instantly at departure, 1 would do.

3. In Car Pooling, why subtract the passengers at to and not at to + 1?

Show answer

Passengers leave at their destination before new passengers board there. Subtracting at to applies the drop-off at that stop, so trips [2, 1, 5] and [3, 5, 7] fit in 3 seats; at to + 1 both groups would be counted in the car at stop 5.

Key takeaways

  • Peak overlap: sort starts and ends separately, sweep, track the running maximum.
  • The tie rule (does an end at t free room for a start at t?) comes from the problem - encode it deliberately.
  • Minimum platforms or rooms equals the maximum overlap.
  • Weighted events: a difference array plus prefix sums, or sorted events with the right tie order.

Quick revise

The whole skill on one page, for the night before an interview.

This page puts the lesson and the deep dive together. Skim it before practice or an interview, and go back to the full lesson for anything you don't recognize.

Pick the tool

You needUse
Peak overlapsort starts and ends, sweep
Small integer timesdifference array
Weighted eventssweep with weights
Room assignmentmin-heap of end times
Peak as bookings arrivesorted map, or a segment tree
Huge coordinatescompress endpoints

Snippets worth knowing by heart

Java

events.sort(Comparator.<int[]>comparingInt(e -> e[0]).thenComparingInt(e -> e[1]));  // ends (-1) first at ties
int cur = 0, best = 0;
for (int[] e : events) { cur += e[1]; best = Math.max(best, cur); }

Python

events = sorted([(s, 1) for s, e in iv] + [(e, -1) for s, e in iv])   # (t, -1) sorts before (t, 1)
cur = best = 0
for _, d in events:
    cur += d
    best = max(best, cur)

The traps

  • The tie rule left to insertion order: back-to-back trains get the wrong platform count. Decide if an end at t frees a start at t.
  • Pairwise checks: comparing every pair is O(n^2) and still doesn't give the peak. Sweep sorted events.
  • Midnight in HHMM: a 2350-0010 train departs "before" it arrives. Use minutes on a timeline past 24:00.
  • Off-by-one in a difference array: an inclusive end's -1 at end drops the last moment. Put it at end + 1.

Staff-level points, one line each

  • The peak is enough rooms (interval graphs are perfect); on 500 sets the heap assigned exactly the peak.
  • Python's (t, -1) sorts before (t, 1), so ends come first, which suits half-open intervals.
  • A Java comparator on time alone kept insertion order: [0, 5) and [5, 10) gave 2 instead of 1.
  • Coordinates up to 10^9: compress endpoints, then use the difference array; it matched the sweep on 300 sets.
  • Online with capacity k: a segment tree with range add and range max, O(log n) a booking; a TreeMap of deltas is O(n).

Say it in an interview

  • "The count at any moment is starts so far minus ends so far, so I sort them separately."
  • "I'll decide what happens when one ends and another starts at the same time, and put it in the sort."
  • "The peak is a lower bound, and greedy assignment shows it's achievable."
  • "For live bookings I'd use a segment tree over compressed times."

Practice

This skill comes with 9 multiple-choice questions that tell you which misconception a wrong answer reveals and 2 graded problems. Your answers are graded and your mastery is tracked, so you'll know when the skill holds up. Running code and saving progress need a free account.

Practice Interval Overlap Counting Greedy free

Minimum Platforms

MediumProCoding problemJava · Python

You are given the arrival and departure times of n trains at a station. Return the minimum number of platforms needed so that no train ever has to wait.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Car Pooling

MediumProCoding problemJava · Python

A shuttle drives one way past stops numbered 0 to 1000. Each trip passengers from to means that many people board at stop from and leave at stop to, and at every stop people get off before others get on.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Practice Interval Overlap Counting Greedy free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime