mediumIntervalsSortingIntervals

Car Pooling

mediumTime: O(n log n)Space: O(n)

Recognize the pattern

enough capacity for all passengers at each stopcumulative passenger countsweep or prefix

Brute force idea

If you approach Car Pooling in the most literal way possible, you get this: Simulate each mile. Extremely slow for long routes. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

A calmer way to see Car Pooling is this: Difference array: for each trip, +passengers at start, -passengers at end. Sweep left to right summing — if any position exceeds capacity, return false. or with event sorting. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Key invariant

The truth you want to protect throughout Car Pooling is this: The difference array captures the net change at each position. A prefix sum gives the actual passenger count at each mile. If it ever exceeds capacity, car pooling isn't possible. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Watch out for

The trap in Car Pooling usually looks like this: Not using a difference array — simulating each trip independently or checking each mile directly is much slower. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Intervals Pattern