#2751
Hard Algorithms Robot collisions
Array Stack Sorting Simulation
56.1% acceptance
Feb 25, 2026
1194
99
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.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn survived_robots_healths(positions: Vec<i32>, mut healths: Vec<i32>, directions: String) -> Vec<i32> {
let n = positions.len();
let dirs: Vec<u8> = directions.bytes().collect();
let mut order: Vec<usize> = (0..n).collect();
order.sort_unstable_by_key(|&i| positions[i]);
let mut stack: Vec<usize> = vec![]; // indices of 'R' moving robots (by position)
for &i in &order {
if dirs[i] == b'R' {
stack.push(i);
} else {
// 'L' robot collides with rightmost 'R' robots
while let Some(&j) = stack.last() {
if healths[j] < healths[i] {
healths[j] = 0;
healths[i] -= 1;
stack.pop();
} else if healths[j] > healths[i] {
healths[j] -= 1;
healths[i] = 0;
break;
} else {
healths[j] = 0;
healths[i] = 0;
stack.pop();
break;
}
}
}
}
(0..n).filter(|&i| healths[i] > 0).map(|i| healths[i]).collect()
}
}