Problem Description
We are given n robots each with a unique position on a line, a health value, and a movement direction (left or right). All robots start moving simultaneously at the same speed. When two robots meet, a collision occurs: the robot with the lower health is removed and the surviving robot loses 1 health. If both have equal health, both are removed. The task is to compute the final healths of the surviving robots and return them in the input order.
Key Insights
- Collisions occur only when a robot moving right encounters a robot moving left.
- Sorting the robots by their positions makes it easier to simulate interactions among approaching robots.
- A stack can be used to keep track of right-moving robots that might collide with a left-moving robot.
- When processing a left-moving robot, it may encounter multiple right-moving robots (from the stack) undergoing sequential collisions.
- The final answer must be reported in the original input order, so tracking the original indices is necessary.
Space and Time Complexity
Time Complexity: O(n), since each robot is processed at most once. Space Complexity: O(n), for storing robot records and the auxiliary stack.
Solution
We first combine each robot's information (position, health, direction, and original index) into a single record and sort these records by position. We then iterate over these sorted records. If the robot is moving right, we push it onto a stack. When a left-moving robot is encountered, we simulate collisions with robots in the right-moving stack:
- While the stack is not empty and the left-moving robot still survives (health > 0), we compare its health with the health of the robot on top of the stack.
- If the left-moving robot’s health is greater, it eliminates the right-moving robot (loses 1 health) and we pop from the stack.
- If both robots have equal health, both are removed.
- If the right-moving robot’s health is greater, it loses 1 health and the left-moving robot is removed. Robots that survive (either left-moving ones that finish collisions or right-moving ones remaining in the stack) are recorded. Finally, we assemble the surviving robots’ health values according to their original order.