Maps app~15 min2s · 256 MBtarget O(n) time, O(1) spacetraversal
You work on a maps app that plans routes for a delivery robot on a city grid. The robot starts at the cell (0, 0), facing north, where north means a larger second number. A route is a string of commands, and the robot repeats the whole route again and again.
Your team lead asks: "Where does the robot stop after it has repeated its route rounds times?" A route can have 100,000 commands, and the robot can repeat it up to 1,000,000,000 times.
Write final_cell(route, rounds).
route is a string of the commands F, L and R.F moves the robot one cell forward, in the direction it faces. L and R turn it 90 degrees left or right, without moving.route from its first command to its last, rounds times in a row, without resetting its position or direction.[x, y], the cell where the robot stops. East is a larger x, and north is a larger y.Input: route = "FRF", rounds = 5
Output: [1, 1]Run the route once at a time and look at where the robot is after each pass.
| After pass | Cell | Facing |
|---|---|---|
| 0 | (0, 0) | north |
| 1 | (1, 1) | east |
| 2 | (2, 0) | south |
| 3 | (1, -1) | west |
| 4 | (0, 0) | north |
After 4 passes the robot faces north again, so the next 4 passes repeat the same move. For 5 passes, take one block of 4 passes, 0 and 0, and then 1 more pass.
Input: route = "R", rounds = 1000
Output: [0, 0]The robot only turns, so it never leaves the cell (0, 0).
Input: route = "FL", rounds = 4
Output: [0, 0]The robot walks a small square and returns to where it started.
1 ≤ len(route) ≤ 100,000, and route holds only F, L and R1 ≤ rounds ≤ 1,000,000,000Following every command costs len(route) × rounds steps, which is 100,000,000,000,000 for the largest input. That is far too many for a 2-second limit. The robot's behaviour must repeat in a short cycle, and you only need to follow the route a few times.