Car Fleet

Hard
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start•← → to step•? all shortcuts

Solution Guide: Car Fleet

Approach

Pair positions with speeds and sort by position. Traverse from the car nearest to target backward, computing each car travel time. If a car needs more time than the fleet ahead, it forms a new fleet; otherwise it merges into the existing fleet.

Complexity Analysis

Time
O(n log n)
Space
O(n)

Pattern

Sort + Monotonic Time Stack

Why It Works

Going right to left ensures every car only interacts with the nearest fleet ahead. Non-increasing fleet times represent merges, while an increased time starts a new fleet.

Updated Mar 2026