💡
Exercise 74

Car Fleet 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

There are n cars heading to a destination target miles away. Each car has a position and speed. A car can never pass another car — it slows down to match. Cars that meet become a fleet.

target = 12 position = [10, 8, 0, 5, 3] speed = [2, 4, 1, 1, 3] # Car at pos 10, speed 2: arrives at (12-10)/2 = 1.0 hours # Car at pos 8, speed 4: arrives at (12-8)/4 = 1.0 hours → same fleet! # Car at pos 5, speed 1: arrives at 7.0 hours # Car at pos 3, speed 3: arrives at 3.0 hours → catches pos 5 → fleet # Car at pos 0, speed 1: arrives at 12.0 hours # Answer: 3 fleets

Strategy using a stack:

  • Sort cars by position (closest to target first)
  • Calculate time to reach target for each car
  • Use a stack: if current car takes longer than the car ahead, it's a new fleet
  • If it takes less/equal time, it joins the fleet ahead (don't push to stack)
📋 Instructions
Implement `car_fleet(target, position, speed)` returning the number of fleets. Test with target=12, position=[10,8,0,5,3], speed=[2,4,1,1,3].
Pair each (position, speed), sort by position descending. Calculate time = (target - pos) / spd for each. Use a stack: push time if it's > stack[-1] (new fleet). Otherwise skip (merges with fleet ahead).
🧪 Test Cases
Input
car_fleet(12, [10, 8, 0, 5, 3], [2, 4, 1, 1, 3])
Expected
3
Test case 1
Input
car_fleet(10, [3], [3])
Expected
1
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.