Skip to main content
medium

Asteroid Collision

Find state of asteroids after all collisions Positive = moving right, Negative = moving left When asteroids collide: smaller explodes, equal = both explode Asteroids moving same direction never meet Example: [5,10,-5] => [5,10] (10 destroys -5)

This is a stack/invariant problem: once your stack represents the right thing, the rest is routine. Interviewers love it because it reveals your stack invariants and your edge-case discipline. The classic mistake is not being clear about what your stack represents at each step.

Examples

You write

asteroid_collision(asteroids: List[int])

  1. Example 1

    Input
    asteroids = [5,10,-5]
    returns
    [5,10]
  2. Example 2

    Input
    asteroids = [8,-8]
    returns
    []

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.

1Asteroid Collisionmedium
2Part 2
3Part 3

Each locked part opens in the editor once the part before it passes.