Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
There are n 1-indexed robots, each having a position on a line, health, and movement direction.
You are given 0-indexed integer arrays positions, healths, and a string directions (directions[i] is either 'L' for left or 'R' for right). All integers in positions are unique.
All robots start moving on the line simultaneously at the same speed in their given directions. If two robots ever share the same position while moving, they will collide.
If two robots collide, the robot with lower health is removed from the line, and the health of the other robot decreases by one. The surviving robot continues in the same direction it was going. If both robots have the same health, they are both removed from the line.
Your task is to determine the health of the robots that survive the collisions, in the same order that the robots were given, i.e. final health of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array.
Return an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur.
Note: The positions may be unsorted.
Example 1:
Input: positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR" Output: [2,17,9,15,10] Explanation: No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10].
Example 2:
Input: positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL" Output: [14] Explanation: There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14].
Example 3:
Input: positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL" Output: [] Explanation: Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, [].
Constraints:
1 <= positions.length == healths.length == directions.length == n <= 1051 <= positions[i], healths[i] <= 109directions[i] == 'L' or directions[i] == 'R'positions are distinctProblem summary: There are n 1-indexed robots, each having a position on a line, health, and movement direction. You are given 0-indexed integer arrays positions, healths, and a string directions (directions[i] is either 'L' for left or 'R' for right). All integers in positions are unique. All robots start moving on the line simultaneously at the same speed in their given directions. If two robots ever share the same position while moving, they will collide. If two robots collide, the robot with lower health is removed from the line, and the health of the other robot decreases by one. The surviving robot continues in the same direction it was going. If both robots have the same health, they are both removed from the line. Your task is to determine the health of the robots that survive the collisions, in the same order that the robots were given, i.e. final health of robot 1 (if survived), final health
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Stack
[5,4,3,2,1] [2,17,9,15,10] "RRRRR"
[3,5,2,6] [10,10,15,12] "RLRL"
[1,2,5,6] [10,10,11,11] "RLRL"
asteroid-collision)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2751: Robot Collisions
class Solution {
public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {
int n = positions.length;
Integer[] indices = new Integer[n];
for (int i = 0; i < n; i++) {
indices[i] = i;
}
Arrays.sort(indices, (i, j) -> Integer.compare(positions[i], positions[j]));
Stack<Integer> stack = new Stack<>();
for (int currentIndex : indices) {
if (directions.charAt(currentIndex) == 'R') {
stack.push(currentIndex);
} else {
while (!stack.isEmpty() && healths[currentIndex] > 0) {
int topIndex = stack.pop();
if (healths[topIndex] > healths[currentIndex]) {
healths[topIndex] -= 1;
healths[currentIndex] = 0;
stack.push(topIndex);
} else if (healths[topIndex] < healths[currentIndex]) {
healths[currentIndex] -= 1;
healths[topIndex] = 0;
} else {
healths[currentIndex] = 0;
healths[topIndex] = 0;
}
}
}
}
List<Integer> result = new ArrayList<>();
for (int health : healths) {
if (health > 0) {
result.add(health);
}
}
return result;
}
}
// Accepted solution for LeetCode #2751: Robot Collisions
func survivedRobotsHealths(positions []int, healths []int, directions string) []int {
n := len(positions)
indices := make([]int, n)
for i := range indices {
indices[i] = i
}
sort.Slice(indices, func(i, j int) bool {
return positions[indices[i]] < positions[indices[j]]
})
stack := []int{}
for _, currentIndex := range indices {
if directions[currentIndex] == 'R' {
stack = append(stack, currentIndex)
} else {
for len(stack) > 0 && healths[currentIndex] > 0 {
topIndex := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if healths[topIndex] > healths[currentIndex] {
healths[topIndex] -= 1
healths[currentIndex] = 0
stack = append(stack, topIndex)
} else if healths[topIndex] < healths[currentIndex] {
healths[currentIndex] -= 1
healths[topIndex] = 0
} else {
healths[currentIndex] = 0
healths[topIndex] = 0
}
}
}
}
result := []int{}
for _, health := range healths {
if health > 0 {
result = append(result, health)
}
}
return result
}
# Accepted solution for LeetCode #2751: Robot Collisions
class Solution:
def survivedRobotsHealths(
self, positions: List[int], healths: List[int], directions: str
) -> List[int]:
n = len(positions)
indices = list(range(n))
stack = []
indices.sort(key=lambda i: positions[i])
for currentIndex in indices:
if directions[currentIndex] == "R":
stack.append(currentIndex)
else:
while stack and healths[currentIndex] > 0:
topIndex = stack.pop()
if healths[topIndex] > healths[currentIndex]:
healths[topIndex] -= 1
healths[currentIndex] = 0
stack.append(topIndex)
elif healths[topIndex] < healths[currentIndex]:
healths[currentIndex] -= 1
healths[topIndex] = 0
else:
healths[currentIndex] = 0
healths[topIndex] = 0
result = [health for health in healths if health > 0]
return result
// Accepted solution for LeetCode #2751: Robot Collisions
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2751: Robot Collisions
// class Solution {
// public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {
// int n = positions.length;
// Integer[] indices = new Integer[n];
// for (int i = 0; i < n; i++) {
// indices[i] = i;
// }
//
// Arrays.sort(indices, (i, j) -> Integer.compare(positions[i], positions[j]));
//
// Stack<Integer> stack = new Stack<>();
//
// for (int currentIndex : indices) {
// if (directions.charAt(currentIndex) == 'R') {
// stack.push(currentIndex);
// } else {
// while (!stack.isEmpty() && healths[currentIndex] > 0) {
// int topIndex = stack.pop();
//
// if (healths[topIndex] > healths[currentIndex]) {
// healths[topIndex] -= 1;
// healths[currentIndex] = 0;
// stack.push(topIndex);
// } else if (healths[topIndex] < healths[currentIndex]) {
// healths[currentIndex] -= 1;
// healths[topIndex] = 0;
// } else {
// healths[currentIndex] = 0;
// healths[topIndex] = 0;
// }
// }
// }
// }
//
// List<Integer> result = new ArrayList<>();
// for (int health : healths) {
// if (health > 0) {
// result.add(health);
// }
// }
//
// return result;
// }
// }
// Accepted solution for LeetCode #2751: Robot Collisions
function survivedRobotsHealths(
positions: number[],
healths: number[],
directions: string,
): number[] {
const idx = Array.from({ length: positions.length }, (_, i) => i);
const stk: number[] = [];
idx.sort((a, b) => positions[a] - positions[b]);
for (let iRight of idx) {
while (stk.length) {
const iLeft = stk.at(-1)!;
const havePair = directions[iLeft] === 'R' && directions[iRight] === 'L';
if (!havePair) break;
if (healths[iLeft] === healths[iRight]) {
healths[iLeft] = healths[iRight] = iRight = -1;
stk.pop();
break;
}
if (healths[iLeft] < healths[iRight]) {
healths[iLeft] = -1;
healths[iRight]--;
stk.pop();
} else {
healths[iRight] = iRight = -1;
healths[iLeft]--;
break;
}
}
if (iRight !== -1) stk.push(iRight);
}
return healths.filter(i => ~i);
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.