Robot Collisions (LeetCode 2751): Solution and Explanation

Hard
Array
Stack
Sorting
Simulation

Robots on a line move left or right at the same speed. When two meet, the weaker one is removed and the stronger loses one health, or both go on a tie. Return the survivors' healths in input order. For Example 2 the answer is [14].

Intuition

This is Asteroid Collision with two twists: the robots are not given in position order, and the winner of a crash loses one health.

Sort the robots by position. Two robots moving the same way never meet, and a left-mover that is left of a right-mover moves away from it. The only crashes are a right-mover followed later in the line by a left-mover.

Sweep left to right with a stack of right-movers that are still alive. A left-mover always hits the nearest one first, which is the stack top. It keeps fighting tops until it is destroyed or no right-mover is left, in which case it escapes.

Approach: Sort + stack simulation

  1. Build a list of robot indexes sorted by position, and copy the healths.
  2. For each robot in that order: if it moves right, push its index.
  3. If it moves left, while it is alive and the stack is not empty, compare it with the top j.
  4. If hp[j] < hp[i], pop j, set hp[j] = 0, and decrement hp[i]. If hp[j] > hp[i], decrement hp[j] and set hp[i] = 0. On a tie, pop j and set both to 0.
  5. Return every positive health, scanning in original index order.

Step-by-step example

positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL"
  1. Position order: robot 3 (x=2, R, 15), robot 1 (x=3, R, 10), robot 2 (x=5, L, 10), robot 4 (x=6, L, 12).
  2. Robot 3 moves right, push. Robot 1 moves right, push. Stack: 3, 1.
  3. Robot 2 moves left and meets robot 1. Both have 10, so both are removed. Stack: 3.
  4. Robot 4 moves left and meets robot 3. 15 > 12, so robot 4 is removed and robot 3 drops to 14.
  5. Survivors in input order: robot 3 with 14. Answer [14].

Code: Python, Java, C++

1class Solution:
2    def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:
3        order = sorted(range(len(positions)), key=lambda k: positions[k])
4        hp = healths[:]
5        stack = []
6        for i in order:
7            if directions[i] == 'R':
8                stack.append(i)
9                continue
10            while stack and hp[i] > 0:
11                j = stack[-1]
12                if hp[j] < hp[i]:
13                    stack.pop()
14                    hp[j] = 0
15                    hp[i] -= 1
16                elif hp[j] > hp[i]:
17                    hp[j] -= 1
18                    hp[i] = 0
19                else:
20                    stack.pop()
21                    hp[j] = 0
22                    hp[i] = 0
23        return [h for h in hp if h > 0]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Sorting dominates. In the sweep each robot is pushed and popped at most once, and each fight either pops a robot or ends the inner loop.

Space

O(n)

The sorted order, the health copy and the stack each take up to n entries.

Other approaches

Event simulation in time (time O(max position * n), space O(n))

Advance time step by step and resolve every meeting. It mirrors the statement but positions reach 10^9, so it is far too slow.

Repeated pass removing adjacent R-L pairs (time O(n^2), space O(n))

Keep scanning the sorted list and resolve any adjacent right-then-left pair until none remain. Correct, but can take O(n^2) in the worst case.

Common mistakes

  • Processing robots in input order instead of position order. Only position order tells you who meets whom.
  • Forgetting that the winner loses 1 health, which can turn a later fight into a tie or a loss.
  • Returning survivors in position order. The answer must follow the original robot numbering.
  • Leaving a dead right-mover on the stack after it loses, or popping a right-mover that won and should keep waiting.

Frequently asked questions

Why can a left-mover only hit the stack top first?

The stack holds alive right-movers in position order, so its top is the closest one to the left-mover. Anything below it is further away and would be reached only after the top is gone.

Do two left-movers or two right-movers ever collide?

No. They move at the same speed in the same direction, so the gap between them never changes.

How is this related to Asteroid Collision?

It is the same stack sweep. Asteroid Collision has sizes instead of healths, the winner does not shrink, and the input is already in position order.