oneby7

Arrays and Hashing Difference arrays

594. Car Pooling

Medium

A car drives east along a straight road and never turns back. Stops on the road are whole numbers: stop x is x kilometres from the start. The car has seats for capacity passengers.

You are given an array trips, where trips[i] = [passengers, pickup, dropoff] means that a group of passengers people gets in at stop pickup and gets out at stop dropoff. Return true if the car can make every trip without ever carrying more than capacity passengers, and false otherwise.

A group is on board from its pickup stop up to its drop-off stop, but not at the drop-off stop itself. So when one group gets out at a stop where another gets in, the first group's seats are free in time.

Example 1

Input: trips = [[3, 1, 5], [2, 4, 8], [4, 5, 9]] capacity = 6

Output: true

Explanation: From stop 4 the car carries 3 + 2 = 5 passengers. At stop 5 the first group gets out and the third gets in, so the car carries 2 + 4 = 6. That is exactly the capacity, and it never carries more.

Example 2

Input: trips = [[2, 0, 3], [3, 1, 4], [2, 2, 6]] capacity = 6

Output: false

Explanation: From stop 2 to stop 3 all three groups are on board, 2 + 3 + 2 = 7 passengers.

Example 3

Input: trips = [[4, 0, 100000], [1, 50000, 50001]] capacity = 4

Output: false

Explanation: The second passenger rides for just one stop, but the first group is still on board then, so the car carries 5.

Check your understanding

Work out the answer for this input before you write any code.

trips = [[4, 2, 6], [3, 6, 9]], capacity = 4

Constraints

  • 1 ≤ trips.length ≤ 105
  • trips[i].length = 3
  • 1 ≤ passengers ≤ 104
  • 0 ≤ pickup < dropoff ≤ 105
  • 1 ≤ capacity ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.