Robot Collisions (LeetCode 2751): Solution and Explanation
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
- Build a list of robot indexes sorted by position, and copy the healths.
- For each robot in that order: if it moves right, push its index.
- If it moves left, while it is alive and the stack is not empty, compare it with the top
j. - If
hp[j] < hp[i], popj, sethp[j] = 0, and decrementhp[i]. Ifhp[j] > hp[i], decrementhp[j]and sethp[i] = 0. On a tie, popjand set both to 0. - 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"
- 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).
- Robot 3 moves right, push. Robot 1 moves right, push. Stack: 3, 1.
- Robot 2 moves left and meets robot 1. Both have 10, so both are removed. Stack: 3.
- Robot 4 moves left and meets robot 3. 15 > 12, so robot 4 is removed and robot 3 drops to 14.
- 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]1class Solution {
2 public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {
3 int n = positions.length;
4 Integer[] order = new Integer[n];
5 for (int k = 0; k < n; k++) order[k] = k;
6 Arrays.sort(order, (a, b) -> Integer.compare(positions[a], positions[b]));
7 int[] hp = healths.clone();
8 Deque<Integer> stack = new ArrayDeque<>();
9 for (int i : order) {
10 if (directions.charAt(i) == 'R') {
11 stack.push(i);
12 continue;
13 }
14 while (!stack.isEmpty() && hp[i] > 0) {
15 int j = stack.peek();
16 if (hp[j] < hp[i]) {
17 stack.pop();
18 hp[j] = 0;
19 hp[i]--;
20 } else if (hp[j] > hp[i]) {
21 hp[j]--;
22 hp[i] = 0;
23 } else {
24 stack.pop();
25 hp[j] = 0;
26 hp[i] = 0;
27 }
28 }
29 }
30 List<Integer> res = new ArrayList<>();
31 for (int h : hp) if (h > 0) res.add(h);
32 return res;
33 }
34}1class Solution {
2public:
3 vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {
4 int n = positions.size();
5 vector<int> order(n);
6 for (int k = 0; k < n; k++) order[k] = k;
7 sort(order.begin(), order.end(), [&](int a, int b) { return positions[a] < positions[b]; });
8 vector<int> hp = healths;
9 vector<int> stack;
10 for (int i : order) {
11 if (directions[i] == 'R') {
12 stack.push_back(i);
13 continue;
14 }
15 while (!stack.empty() && hp[i] > 0) {
16 int j = stack.back();
17 if (hp[j] < hp[i]) {
18 stack.pop_back();
19 hp[j] = 0;
20 hp[i]--;
21 } else if (hp[j] > hp[i]) {
22 hp[j]--;
23 hp[i] = 0;
24 } else {
25 stack.pop_back();
26 hp[j] = 0;
27 hp[i] = 0;
28 }
29 }
30 }
31 vector<int> res;
32 for (int h : hp) if (h > 0) res.push_back(h);
33 return res;
34 }
35};Time and space complexity
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.
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.