LeetCode 2751 – Robot Collisions
Robot Collisions
Problem Statement
There are n robots, each numbered from 1 to n.
You are given 0-indexed integer arrays positions, healths,
and a string directions. All integers in positions are unique.
All robots start moving simultaneously at the same speed in their given directions. If two robots ever share the same position, a collision takes place with the following rules:
- • The robot with lower health is removed. The surviving robot's health decreases by 1.
- • If both robots have equal health, both are removed.
Return an array of the healths of the remaining robots after all collisions, in the order they were given. If no robots remain, return an empty array.
- 1 ≤ n ≤ 105
- 1 ≤ positions[i], healths[i] ≤ 109
- directions[i] is either
'L'or'R' - All values in positions are distinct
Intuition
Think of the stack as a waiting room for right-movers.
Every robot going R sits in the waiting room.
When a L-mover arrives, it is on a collision course with
whoever is at the front of that room.
The left-mover keeps fighting until one of three things happens:
R loses 1, L dies (hp=0)
R dies (hp=0, popped), L loses 1
Both set to 0, R popped
healths[top] = 0 before popping.
The final collection loop checks healths[i] > 0 — if you forget to zero it,
a dead right-mover gets counted as a survivor.
Step-by-Step Simulation
Using Example 2: positions=[1,40], healths=[10,11], directions="RL"
⚡
healths[R0] = 0 (zeroed + popped) | healths[R1] = 11 - 1 = 10. Stack empty → loop exits.Execution Trace Table
| Step | Current robot | Stack top | Comparison | Action | Stack state |
|---|---|---|---|---|---|
| 1 | R0 (R, hp=10) | — | direction = R | PUSH R0 | [R0] |
| 2 | R1 (L, hp=11) | R0 (hp=10) | 11 > 10 | R1 wins, R0 hp=0, POP | [] |
| 3 | R1 (L, hp=10) | — | stack empty | — | [] |
| 4 | Collect: healths[0]=0 (skip), healths[1]=10 → result = [10] | ||||
Java Solution
Complexity Analysis
Alternative Approaches
- Clean O(n) collision step
- Each robot enters stack once
- Straightforward to implement
- Sorting needed upfront
- Index-tracking is tricky
- Very easy to reason about
- Matches problem description 1:1
- Extremely slow for large inputs
- Depends on max health value
- Generalizes to harder variants
- Natural priority ordering
- Overcomplicated for this problem
- Hard to preserve original order
Common Mistakes
healths[top] = 0 before poppingstack.pop() removes it from future collisions but leaves its health positive. The final loop then incorrectly includes it as a survivor. Always zero the health before popping.positions[i] first, then process. Skipping the sort produces wrong collision sequencing.i=0 to n-1 (original indices), not over the sorted index array. The problem explicitly asks for the order they were given.