← Whiteboard questions

Car Fleet

Count the groups of cars that arrive together

DSA, Medium, Stack

Which structure or algorithm, and what does it cost.

Cars drive along one lane toward a town at position town. Car i starts at starts[i] and drives at a steady speeds[i]. Cars cannot overtake. A car that closes the gap to the car ahead drops to that car's speed, and the two drive on as one fleet. A car that only reaches the car ahead at the town itself is still part of that fleet. Return how many fleets get to the town. Positions are in kilometres and speeds are in kilometres per hour.

Examples

Input town = 14, starts = [1, 4, 6, 8], speeds = [3, 2, 1, 2]
Output 2
Why the car at 8 arrives alone after 3 hours. Alone, the cars at 6, 4 and 1 would need 8, 5 and about 4.3 hours, so the last two catch the car at 6 and share its 8 hours.
Input town = 26, starts = [16, 5, 11], speeds = [1, 3, 3]
Output 1
Why the cars are not listed in road order. The car at 16 needs 10 hours. The car at 11 would need 5 alone, so it is held to 10. The car at 5 would need 7: more than 5, but less than the 10 of the fleet it meets, so it joins too.
Input town = 9, starts = [3, 6], speeds = [2, 1]
Output 1
Why both cars need 3 hours, so the back car reaches the front car exactly at the town. That counts as one fleet.

Constraints

Your answer must contain

Target Aim for O(n log n) time and O(n) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Think about when a car would reach the town on an empty road. A car stuck behind a slower one cannot arrive before that one.

Hint 2 the approach

Sort the cars by starting position, and look at them from the car nearest the town back toward the start.

Hint 3 the key step

Go from the car nearest the town and remember one time: the arrival time of the fleet just ahead. When can the next car never reach that fleet?

Walkthrough

Full walkthrough brute force to best

Brute force

For each car, find its true arrival time: the largest empty-road time among itself and every car ahead of it, because it can never beat a slower car in front. Count the different true times. Each car checks every car ahead, so this is O(n^2) time. With 80,000 cars that is about 3 billion comparisons.

Best method

A car can never arrive before a slower car ahead of it, so what matters is each car's empty-road time: the distance to the town divided by the speed. Sort the cars by starting position and go from the one nearest the town. Keep a stack of arrival times, one per fleet. A car whose time is longer than the top of the stack can never catch that fleet, so it starts a new fleet and is pushed. A car whose time is equal or shorter catches the fleet ahead by the town and joins it, so nothing is pushed. The stack size at the end is the number of fleets. Do not round the times, because two different times can be very close. Plain division is exact enough for these limits; exact fractions or cross multiplication also work. Only the top is ever read, so a single variable works as well.

Hand trace

Run on example 1 with the town at 14. Nearest the town first, the cars are: position 8 speed 2, position 6 speed 1, position 4 speed 2, position 1 speed 3. Car at 8: time 6 / 2 = 3. The stack is empty, so push. Stack [3]. Car at 6: time 8 / 1 = 8, longer than 3, so push. Stack [3, 8]. Car at 4: time 10 / 2 = 5, not longer than 8, so it joins that fleet. Car at 1: time 13 / 3, about 4.33, not longer than 8, so it joins too. The stack holds 2 times, so the answer is 2.

Code

from fractions import Fraction
def car_fleet(town, starts, speeds):
    cars = sorted(zip(starts, speeds), reverse=True)    # nearest the town first
    stack = []                                           # arrival time of each fleet
    for p, s in cars:
        time = Fraction(town - p, s)
        if not stack or time > stack[-1]:
            stack.append(time)
    return len(stack)

Time and memory

O(n log n) time for the sort, then O(n) for the single pass. O(n) memory for the sorted list and the stack.

Common mistakes

  • Using the speeds alone to decide who catches whom, or comparing each car only with the car just ahead of it. That car may already be held back by a slower fleet, so compare with the fleet's arrival time: a longer time means the car stays behind.
  • Counting a car that meets the front car exactly at the town as a new fleet. Equal times join, so push only when the time is strictly longer. Example 3 checks this.
  • Rounding the times before you compare them, for example to two decimals. Compare the full division results. Exact fractions or cross multiplication remove any doubt.
  • Forgetting to sort. The cars come in any order, and the idea needs the road order.

Related problems

More Stack problems
Car Fleet: hints, walkthrough and Python solution