Car Fleet - Problem

There are n cars at given miles away from the starting mile 0, traveling to reach the mile target. You are given two integer arrays position and speed, both of length n, where position[i] is the starting mile of the ith car and speed[i] is the speed of the ith car in miles per hour.

A car cannot pass another car, but it can catch up and then travel next to it at the speed of the slower car. A car fleet is a single car or a group of cars driving next to each other. The speed of the car fleet is the minimum speed of any car in the fleet.

If a car catches up to a car fleet at the mile target, it will still be considered as part of the car fleet. Return the number of car fleets that will arrive at the destination.

Input & Output

Example 1 — Multiple Fleets
$ Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
Output: 3
💡 Note: Car at position 10 (speed 2) takes 1.0 time. Car at position 8 (speed 4) takes 1.0 time, joining the first fleet. Car at position 5 (speed 1) takes 7.0 time, forming a new fleet. Cars at positions 3 and 0 join existing fleets based on their arrival times.
Example 2 — Single Fleet
$ Input: target = 10, position = [3], speed = [3]
Output: 1
💡 Note: Only one car, so it forms one fleet by itself.
Example 3 — No Catching Up
$ Input: target = 100, position = [0,2,4], speed = [4,2,1]
Output: 1
💡 Note: All cars take 25.0, 49.0, and 96.0 time respectively. The fastest car catches up to others, forming one large fleet.

Constraints

  • n == position.length == speed.length
  • 1 ≤ n ≤ 105
  • 0 < target ≤ 106
  • 0 ≤ position[i] < target
  • All the values of position are unique
  • 0 < speed[i] ≤ 106

Visualization

Tap to expand
Car Fleet Problem OverviewStart (0)Target (12)C1pos=0, spd=1C2pos=3, spd=3C3pos=5, spd=1C4pos=8, spd=4C5pos=10, spd=2↓ Calculate Arrival Times ↓12.0 hours3.0 hours7.0 hours1.0 hours1.0 hours↓ Fleet Formation ↓Fleet 1C4 + C5 (1.0h)Fleet 2C2 (3.0h)Fleet 3C3 + C1 (7.0h+)Result: 3 Fleets
Understanding the Visualization
1
Input
Cars at different positions with various speeds heading to target
2
Process
Faster cars catch up to slower ones, forming fleets
3
Output
Count of distinct car fleets reaching destination
Key Takeaway
🎯 Key Insight: Cars closer to target determine fleet speed - work backwards from finish line!
Asked in
Amazon 45 Google 38 Microsoft 32 Facebook 28
168.4K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen