Skip to content
Problem 1094 · LeetCode 1094(opens in a new tab)

Car Pooling

MediumArrays

A car with capacity free seats drives east along a road and never turns back. Each entry of trips is [passengers, start, end]: that many people get in at kilometre start and get out at kilometre end.

At the same kilometre, people get out before new people get in. Return true if the car can complete every trip without ever carrying more than capacity people, and false otherwise.

Example 1

Input:  trips = [[3, 0, 4], [2, 2, 6], [4, 5, 8]], capacity = 5
Output: false
Why:    at km 5 the car holds 2 + 4 = 6 people
2 more examples and the constraints

Example 2

Input:  trips = [[3, 0, 4], [2, 2, 6], [4, 5, 8]], capacity = 6
Output: true
Why:    the most people at once is 6

Example 3

Input:  trips = [[4, 1, 3], [4, 3, 5]], capacity = 4
Output: true
Why:    the first group gets out at km 3 before the second gets in

Constraints

  • 1 ≤ number of trips ≤ 1,000
  • 1 ≤ passengers ≤ 100
  • 0 ≤ start < end ≤ 1,000
  • 1 ≤ capacity ≤ 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check every pickupO(n²)
  2. Difference arrayO(n + L)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 tripsVerdict
Check every pickupO(n²)
Mention it, then move on
Difference arrayO(n + L)
Best; two short loops

n = number of trips, L = number of kilometres (1,001).

Edge cases to test

  • Drop-off and pickup at the same kilometre. [[4, 1, 3], [4, 3, 5]] with 4 seats is true: the end is exclusive.
  • One trip larger than the car. [[7, 0, 1]] with 6 seats is false right away.
  • Trips that never overlap. Only the largest single group matters.
  • Exactly full. A load equal to capacity is allowed; only going over fails.

Common mistakes

  • Treating the end kilometre as still in the car, so back-to-back trips look like they overlap.
  • Failing when the load equals capacity instead of only when it is greater.
  • Sorting events with pickups before drop-offs at the same kilometre.

How to talk through it

  1. 1Clarify. Do people get out before others get in at the same kilometre? Is the road at most 1,000 km?
  2. 2Give the simple check. The car is fullest at some pickup; checking each pickup is O(n²).
  3. 3Record changes. +p at start, −p at end, in an array by kilometre.
  4. 4Sweep once. A running sum gives the load everywhere. O(n + L) time.
  5. 5Test out loud. Run back-to-back trips and an exactly full car.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?