InterviewHubPRO
Section Overview
Q36

Question 36 of 100

Part 4: Stacks, Queues & Monotonic Stacks (29 - 36)

36%
DSA Patterns (Multi-Lang)•Part 4: Stacks, Queues & Monotonic Stacks (29 - 36)

Car Fleet.

In Simple Words: Sort cars by starting position descending (closest to target first). Compute time to destination (target - pos) / speed. If a car arrives in $\le$ time of car ahead, it joins the fleet ahead.

  • Time: $O(N \log N)$ | Space: $O(N)$
Multi-Language Solutions
Switch tabs or choose All
def carFleet(target: int, position: list[int], speed: list[int]) -> int:
    cars = sorted(zip(position, speed), reverse=True)
    stack = []
    for p, s in cars:
        time = (target - p) / s
        if not stack or time > stack[-1]:
            stack.append(time)
    return len(stack)