Car Fleet

MediumStack

Problem

Cars are heading to the same destination along a one-lane road, each with a starting position and speed. A car can never pass the car ahead of it; if a faster car catches up to a slower one, they merge into a single fleet moving at the slower speed. Return the number of distinct fleets that will arrive at the destination.

Examples

Example 1
Input:target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
Output:3

Constraints

  • n == position.length == speed.length
  • 1 <= n <= 10^5

Solve it in the editor. Sign in free to run your Python or JavaScript against test cases, get a verdict, and track your attempts.

Solve on FeatCode →

How to approach it: the Stack pattern

A stack is last-in-first-out — the most recently added item is the first one removed. It's the natural fit whenever "the most recent unmatched thing" matters, like nested brackets or undo history.

Look for this pattern when

  • You're validating nested or paired structures (parentheses, tags, nested expressions).
  • You need to track "the most recent X that hasn't been resolved yet."
  • You're looking for the next larger or smaller element relative to each position.

Read the full Stack guide →

Video walkthroughs

Original problem on LeetCode ↗

More Stack problems