Young Devs Bin
๐Ÿ“ Today I Learned

Car Pooling: Weighted Sweep, Bounded Coordinates, and Knowing Who Broke Capacity

ยท2 min readยท#today-i-learned#algorithm#heap#sweep-line#leetcode#python

Picked up Car Pooling โ€” it's Meeting Rooms II wearing a different hat, weighted by passenger count instead of just +1/-1.

  • The core shift from Meeting Rooms: a trip doesn't add 1 to the running count, it adds numPassengers โ€” same +/- event logic, bigger stickers
  • Stations are bounded at 0-1000, and that constraint is the whole game โ€” it's what unlocks a bucket array instead of sorting: one slot per station, +p at pickup, -p at drop-off, one pass accumulating and checking against capacity
  • Drop-offs have to be processed before pickups at the same station โ€” in the bucket version this happens automatically since -p and +p land in the same slot and cancel before I read it; in the sorted-events version, storing drop-offs as negative numbers makes the tuple sort put them first at a tie
  • If station coordinates were unbounded, the bucket array breaks โ€” I'd fall back to sorting events, same sweep logic, just O(n log n) instead of O(n + range)
  • The bucket array is anonymous โ€” it can tell me HOW MANY passengers are on board, but not WHICH trip caused an overflow. To answer that, I need to process trips one by one, keeping their original index, with a min-heap of (drop_off, passengers) for whoever's currently on board
  • That heap version needed a while loop, not an if, to free seats โ€” the gap between two pickups can span multiple drop-off points, so more than one group might need to get off before the next trip boards. Same reasoning as Meeting Rooms III, one day ahead of actually reaching it
  • Wrote a bug into my own code by reusing the loop variable p inside the while block โ€” it silently overwrote the outer loop's "passengers boarding now" with "passengers just leaving," and count += p picked up the wrong number. Renaming the inner one to leaving fixed it. Lesson: never reuse an outer loop variable name inside a nested loop that's popping/assigning things