Robot Collisions - Stack [JS]
Solution: Stack
Note: The positions don't affect which robots will collide with each other, this stays the same no matter what. Robots adjacent to each other going right and left will always collide.
In the stack, keep track of robots we have processed so far that have still survived.
If the current robot is going left,
- We need to eliminate all right-going robots with smaller health at the top of the stack, while decreasing the health of the current robot.
- If the robot at the top of the stack is right-going and the health is greater, then remove the current robot and decrease the health of the robot at the top of the stack.
- If the robot at the top of the stack is right-going and the health is the same, remove both.
If the current robot is going right, then just push it onto the stack to be dealt with later.
n = number of robots
Time Complexity: O(n log(n))
Space Complexity: O(n)
var survivedRobotsHealths = function(positions, healths, directions) {
let n = positions.length, stack = [], robots = [];
for (let i = 0; i < n; i++) {
robots.push({position: positions[i], health: healths[i], direction: directions[i], originalIndex: i})
}
robots.sort((a, b) => a.position - b.position);
for (let i = 0; i < n; i++) {
if (robots[i].direction === 'L') {
// remove right-going robots with smaller health from the top of the stack while decreasing the current robot's health
while (stack.length && robots[stack[stack.length - 1]].direction === 'R' && robots[stack[stack.length - 1]].health < robots[i].health) {
stack.pop();
robots[i].health--;
}
if (stack.length === 0 || robots[stack[stack.length - 1]].direction === 'L') stack.push(i); // no more collisions, add current robot to stack
else if (stack.length > 0 && robots[stack[stack.length - 1]].health === robots[i].health) stack.pop(); // health is same, remove both
else if (stack.length > 0 && robots[stack[stack.length - 1]].health > robots[i].health) robots[stack[stack.length - 1]].health--; // right-going robot has greater health, remove current robot and decrease right-going robot's health
} else {
stack.push(i);
}
}
return stack.sort((a, b) => robots[a].originalIndex - robots[b].originalIndex).map((i) => robots[i].health);
};
Comments
Post a Comment