Ctrl K

Robots Clashing on a Rail

Medium
Robots ride along a straight rail, all at the same speed. The array robots lists them from left to right: the absolute value is a robot's mass and the sign is its direction (positive means right, negative means left). There are no zeros. When two robots moving towards each other meet, the lighter one breaks and leaves the rail while the heavier one keeps going. If their masses are equal, both break. Robots moving in the same direction never catch up with each other. Return the robots that remain after all collisions, from left to right.
Example 1
robots=[4, -2, 6, -6, -5] → [-5]

4 meets -2, and -2 breaks. 6 and -6 are equal, so both break. Then 4 meets -5 and breaks. Only [-5] is left.

Example 2
robots=[-3, -1, 2, 7] → [-3, -1, 2, 7]

The left ones drive left and the right ones drive right, so nobody ever meets.

Example 3
robots=[5, 3, -4] → [5]
Constraints
  • 2 ≤ len(robots) ≤ 10⁵
  • -1000 ≤ robots[i] ≤ 1000
  • robots[i] ≠ 0
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsReplaying Stack Pushes and Pops MediumA Stack From a Number Stream MediumQuiz Score Log EasyA Picky Line at the Counter EasyRobots Crashing on a Rail Hard
loading Python…
Input
robots=[4, -2, 6, -6, -5]
Expected
[-5]

Run checks the first 3 tests in your browser. Submit checks all 125 tests on the server, hidden ones included.