Python coding

Convoys at the finish line

Cars drive along a one-lane road toward a finish line at point target. Car i starts at point position[i] and drives at a constant speed[i]. No car can pass another: when a car catches up with a slower one ahead, it slows down and both go on as one convoy at the speed of the car in front. A lone car is a convoy too, and cars that meet exactly at the finish line arrive as one convoy. Return how many convoys cross the finish line.

Constraints: both lists have the same length, possibly 0; positions are distinct, 0 <= position[i] < target <= 10^6, 1 <= speed[i] <= 100. Aim for O(n log n).

Besides the tests, one large input (3,500 cars) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • count_convoys(20, [14,10,2,6], [2,4,1,3]) → 3
  • count_convoys(100, [0,10,20,30], [4,3,2,1]) → 1
  • count_convoys(12, [0,6], [2,1]) → 1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Sort the cars by starting position. A car joins the convoy ahead exactly when, driving alone, it would reach the finish no later than that convoy.

Hint 2

Go from the back of the road to the front with a stack of arrival times (target - p) / s. Each new car pops every time <= its own: those cars catch it.

Hint 3

The stack ends with one arrival time per convoy, so its length is the answer. Use <=, not <: cars that meet at the finish line form one convoy.

Solution and why it works
pythonO(n log n) · O(n)
def count_convoys(target: int, position: list[int], speed: list[int]) -> int:
    stack = []                                   # one arrival time per convoy, decreasing
    for p, s in sorted(zip(position, speed)):    # from the back of the road to the front
        t = (target - p) / s                     # when this car would arrive alone
        while stack and stack[-1] <= t:
            stack.pop()                          # that convoy catches this car: they merge
        stack.append(t)
    return len(stack)

A convoy arrives when its front car would arrive alone, so only arrival times matter. Sorted from the back of the road, each car pops every convoy behind it that would arrive no later, since that convoy catches it before the line. The stack keeps decreasing times, one per convoy; each car is pushed and popped once, so sorting dominates: O(n log n). Traps: skipping the sort, using < (a tie at the line is one convoy), and comparing speeds instead of arrival times.