Skip to main content

Car Fleet

Given target position, car positions, and speeds Return number of car fleets that will arrive at destination Cars can't pass but can catch up and form fleets Example: target=12, position=[10,8,0,5,3], speed=[2,4,1,1,3] => 3

Car Fleet is all about maintaining a clear stack meaning as you process input. Interviewers love it because it reveals your stack invariants and your edge-case discipline. Keep the stack invariant explicit; if it breaks, everything downstream breaks too.

Examples

You write

car_fleet(target: int, position: List[int], speed: List[int])

  1. Example 1

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

    Input
    target = 10, position = [3], speed = [3]
    returns
    1

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Stack

I reach for it when

  • Things must close in the reverse order they opened.
  • You need the nearest earlier or later item that is bigger or smaller.

Say this before you type. Say what each item on the stack is waiting for, and what lets you pop it.

All 17 Stack problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Car Fleetmedium