DSA Factory
Free Intervals lessonsIntervals · Stage 1 · Sweep line · Step 4

Does the car pool fit?

Check whether a car with limited seats can carry every trip, by adding passengers at each pick-up and removing them at each drop-off while sweeping through time. About 20 minutes.

Weighted events

A car has a number of seats. Each trip carries some passengers from a pick-up point to a drop-off point along a road. Can the car do all the trips?

This is the earlier sweep with weights. At the pick-up point the passenger count goes up by the trip's passengers. At the drop-off it goes down by the same amount. Passengers dropped at a point leave before new ones board there.

Pick-up: adds the trip's passengers.
Drop-off: removes them again, before pick-ups at that point.

Check the peak

Sort the events by position, and by amount at the same position, so that negative amounts come first. Walk through, adding the amounts to a running load.

If the load ever goes above the number of seats, the answer is no. If you reach the end without that, the answer is yes. Only the highest load matters, not where it occurs.

Load above the seats? return false at once.
Reached the end? return true.
In code
load += change
if load > seats:
    return False
Seats 5. Trips: 2 passengers from 1 to 4, 3 passengers from 2 to 6, 2 passengers from 5 to 8.
12345678[1, 4][2, 6][5, 8]

At point 1: pick up 2. The load is 2, which is within 5 seats.

Move 1 of 4
Quick check

Seats 3. One trip carries 3 people from 2 to 4, another carries 3 from 4 to 6. Does it fit?

  1. AYes
  2. BNo
  3. COnly with 6 seats
Show the answer

Yes. At point 4 the first group leaves before the second boards.

Your problem

Car pooling

A car has capacity empty seats and drives in one direction. You are given trips, where trips[i] = [passengers, from, to]: passengers people board at position from and leave at position to. Return true if the car can complete all the trips without ever carrying more than capacity people. People leave before new ones board at the same position.

Example
trips = [[2, 1, 5], [3, 3, 7]], capacity = 4 → false

0 ≤ trips.length ≤ 100,000 · 1 ≤ passengers ≤ 100 · 0 ≤ from < to ≤ 1,000,000 · 1 ≤ capacity ≤ 100,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve