Search lands in PR-5.1 (Pagefind).

How-to Intermediate

Chapter 2 Updated

Car Pooling

Sweep events or difference array; reject as soon as load exceeds capacity.

  • Full 5m
  • Revision
  • Flow

Problem Statement

Given a list of trips [numPassengers, from, to] and a car with a fixed capacity, determine whether the car can make every pickup and drop-off along the route without ever exceeding capacity.

Input

  • trips — each entry [p, s, e] picks up p passengers at location s, drops them off at location e.
  • capacity — integer seat capacity.
Example input
trips = [[2,1,5],[3,3,7]], capacity = 4

Output

A boolean: true if the trip sequence is feasible, false if capacity is exceeded at any point.

Expected output
false

Constraints

  • 1 ≤ trips.length ≤ 1000
  • 0 ≤ trips[i][0] ≤ 100 (passengers per trip)
  • 0 ≤ trips[i][1] < trips[i][2] ≤ 1000 (locations)
  • 1 ≤ capacity ≤ 10⁵

Intuition

Two interchangeable lenses — both are sweep-line at heart:

  • Sweep line: each trip produces a +p event at pickup and a -p event at drop-off. Sort events by location, sweep, reject as soon as the running load exceeds capacity.
  • Difference array: because locations are bounded 0…1000, use a fixed array diff[], do diff[s] += p and diff[e] -= p in O(1), then prefix-sum the array to get the load at every point.
Locations 0…1000, trips [[2,1,5],[3,3,7]]
diff after updates:  [0, +2, 0, +3, 0, -2, 0, -3, 0, …]
Prefix sums:         [0,  2, 2,  5, 5,  3, 3,  0, …]
                               ↑ exceeds capacity 4 → return false

Solution

car_pooling_sweep.py
def carPooling(trips: list[list[int]], capacity: int) -> bool:
    events = []
    for p, s, e in trips:
        events.append((s, p))
        events.append((e, -p))
 
    events.sort()
    cur = 0
    for _, delta in events:
        cur += delta
        if cur > capacity:
            return False
 
    return True

Complexity

MetricValueReason
Time (sweep)O(n log n)Sorting 2n events
Time (diff array)O(n + max)Linear over trips + fixed-size array walk
SpaceO(n) / O(max)Events list or fixed-size buffer

Edge Case Thinking

ScenarioHandling
Single trip with p ≤ capacityPeak load = p → always true.
Overlap exactly at drop-off [_, 1, 5] & [_, 5, 10]Drop-off processed before pickup at location 5 → load is released first.
Diff-array scalingFalls back to sweep line when coordinates exceed 1000.
Reject earlyDiff-array version can short-circuit as soon as cur > capacity.
Passenger count 0No-op — events cancel; doesn’t affect feasibility.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.