Skip to content

Car Pooling

Check a car never goes over capacity by turning trips into pick-up and drop-off events and sweeping them.

MediumIntervals
Solve on LeetCode

The problem

A car with capacity empty seats drives east along a road and never turns back. Each trip trips[i] = [numPassengers, from, to] means that many passengers get in at kilometre from and get out at kilometre to. Return true if the car can complete all trips without ever carrying more than capacity passengers at once, and false otherwise.

Input trips = [[3, 2, 7], [2, 4, 9], [1, 7, 10]], capacity = 4

Output false

Between kilometres 4 and 7 the car carries 3 + 2 = 5 people, one more than its 4 seats.

Input trips = [[4, 1, 6], [4, 6, 8]], capacity = 4

Output true

The first group gets out at kilometre 6 just as the second group gets in, so there are never more than 4 people inside.

Key constraint: Passengers who get out at a point leave before new passengers get in at that same point.

How to spot the pattern

  • Many intervals each add a load over a range, and you need the peak load at any moment.
  • Only the points where something changes (a pick-up or a drop-off) matter.

The idea

The number of people in the car only changes at pick-up and drop-off points. So turn each trip into two events: +passengers at from and -passengers at to. Sort the events by location, with drop-offs before pick-ups at the same location, and walk through them keeping a running count; if it ever goes above capacity, the trips don't fit.

Brute force: For every kilometre from the first pick-up to the last drop-off, add up the passengers of every trip that covers it, which is O(L * n) for L kilometres.

Step by step

  1. 1For each trip, add the events (from, +passengers) and (to, -passengers).
  2. 2Sort the events by location and, at equal locations, put the negative changes first.
  3. 3Walk through the events, adding each change to a running passenger count.
  4. 4If the count is ever more than capacity, return false; if the walk finishes, return true.

See the pattern move

The intervals pattern on a small example. Step through it, or press play.

Code

class Solution:
    def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
        events = []  # (location, change in passengers)
        for passengers, start, end in trips:
            events.append((start, passengers))
            events.append((end, -passengers))
        # Sorting tuples puts drop-offs (negative changes) first at the same location.
        events.sort()
        inside = 0
        for _, change in events:
            inside += change
            if inside > capacity:
                return False
        return True

Complexity

Time

O(n log n)

Space

O(n)

Sorting the 2n events dominates; the sweep is one pass over them.

Watch out for

  • Processing pick-ups before drop-offs at the same location, which counts both groups in the car at once and wrongly returns false for trips like [[4, 1, 6], [4, 6, 8]] with 4 seats.
  • Checking each trip against capacity on its own: the limit applies to everyone in the car at the same time.
  • Walking the trips in input order without sorting the events, which misses overlaps between trips listed far apart.

Follow-up questions

Locations are at most 1,000. Can you avoid sorting?

Yes: use a difference array of size 1,001. Add passengers at from, subtract it at to, then take a running sum and compare every prefix with capacity. That is O(n + L) for L locations.

How many meeting rooms do you need for a list of meetings?

Run the same sweep with +1 at each start and -1 at each end (ends first on ties); the highest running count is the number of rooms. That is Meeting Rooms II.

In Hinglish

Har trip ko do events mein todo: chadhna (+) aur utarna (-). Location ke hisaab se sort karo, same jagah par pehle utaro, aur running count capacity se upar gaya toh false.

Related problems