Robot Collisions - Problem

There are n robots positioned on a line, each with a unique position, health value, and movement direction.

You are given three inputs:

  • positions: array of robot positions (0-indexed, unsorted)
  • healths: array of robot health values
  • directions: string where each character is 'L' (left) or 'R' (right)

All robots move simultaneously at the same speed. When two robots collide:

  • The robot with lower health is removed
  • The surviving robot's health decreases by 1
  • If both have equal health, both are removed

Return the final health values of surviving robots in their original input order. If no robots survive, return an empty array.

Input & Output

Example 1 — Basic Collision
$ Input: positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR"
Output: [2,17,9,15,10]
💡 Note: All robots move right in same direction, so no collisions occur. All survive with original health.
Example 2 — Head-on Collision
$ Input: positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL"
Output: [14]
💡 Note: After sorting by position: R(H:15) at pos 2, L(H:10) at pos 3, R(H:10) at pos 5, L(H:12) at pos 6. Multiple collisions result in one survivor with health 14.
Example 3 — No Survivors
$ Input: positions = [1,2,3,4,5], healths = [1,1,1,1,1], directions = "RLRLR"
Output: []
💡 Note: Alternating directions with equal health cause all robots to destroy each other in collisions.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ positions[i] ≤ 109
  • 1 ≤ healths[i] ≤ 109
  • directions[i] is either 'L' or 'R'
  • All values in positions are distinct

Visualization

Tap to expand
Robot Collisions - Stack-Based Solution INPUT 1 2 3 4 5 2 17 9 15 10 positions: 5 4 3 2 1 healths: 2 17 9 15 10 directions: R R R R R All robots moving RIGHT No collisions possible! ALGORITHM STEPS 1 Sort by Position Order robots by position 2 Use Stack Track R-moving robots 3 Check Collisions L meets R = collision 4 Return Survivors Original order preserved Stack Processing: All R: No collisions Stack: [all robots] Result: unchanged FINAL RESULT All Robots Survive! 2 pos:5 17 pos:4 9 pos:3 15 pos:2 10 pos:1 Output Array: [2, 17, 9, 15, 10] Original input order Why No Collisions? All robots move RIGHT Same direction = same speed They never catch each other OK Key Insight: Collisions only occur when a RIGHT-moving robot meets a LEFT-moving robot coming toward it. Since all robots move RIGHT (same direction), they maintain relative positions forever. Time Complexity: O(n log n) for sorting | Space Complexity: O(n) for stack TutorialsPoint - Robot Collisions | Stack-Based Collision Detection
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
32.4K Views
Medium-High Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen