Ctrl K

When Rail Robots Catch Up

Hard
Robots move along a single rail, all in the same direction. robots[i] = [position, speed]: robot i starts position metres from the start of the rail and moves at speed m/s. The robots are listed in increasing order of starting position, and all positions are distinct. Treat the robots as points. When a robot reaches the one directly ahead of it, they lock together and keep moving as one, at the speed of the slowest robot in the group. Return an array whose i-th element is the time in seconds at which robot i reaches the robot directly ahead of it, or -1 if that never happens. Answers within 10⁻⁵ of the exact value are accepted.
Example 1
robots=[[2, 3], [5, 1], [6, 2]] → [1.5, -1, -1]

Robot 0 reaches robot 1 after (5 − 2) / (3 − 1) = 1.5 seconds. Robot 1 is slower than robot 2 and never reaches it, and robot 2 has nobody ahead, so both get -1.

Example 2
robots=[[1, 4], [3, 3], [4, 1]] → [1.0, 0.5, -1]

Robot 1 reaches robot 2 after 0.5 s, and from then on they move together at speed 1. Robot 0 would need 2 s to reach robot 1 at its old speed, but it has slowed down: they actually meet after 1 second, at position 5.

Example 3
robots=[[10, 7]] → [-1]
Constraints
  • 1 ≤ len(robots) ≤ 10⁵
  • 1 ≤ position, speed ≤ 10⁶
  • Positions are strictly increasing
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSecond Larger to the Right HardLong Leaps Across a Board HardFirst Common Rooftop HardWater Between Walls HardBiggest Rectangle Under the Skyline Hard
loading Python…
Input
robots=[[2, 3], [5, 1], [6, 2]]
Expected
[1.5, -1, -1]

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