Monitoring~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-189traversal
The monitoring app of a web service shows a row of dashboard tiles. Each tile has a number, its id. When an operator presses "next page", every tile moves one place to the right, and the last tile wraps round to the front.
A script can press the key up to 1,000,000,000 times. The app has little memory to spare, so it should change the row itself and not build a second one.
Write rotate_tiles(tiles, k).
tiles[i] is the id of the tile at place i.k is the number of key presses.tiles to the right by k places in place, and return it.Input: tiles = [4, 8, 15, 16, 23, 42], k = 2
Output: [23, 42, 4, 8, 15, 16]Reverse the whole row, then reverse the first k tiles, then reverse the rest.
| Step | What you do | Row after the step |
|---|---|---|
| 1 | k = 2 mod 6 = 2 | [4, 8, 15, 16, 23, 42] |
| 2 | reverse all 6 tiles | [42, 23, 16, 15, 8, 4] |
| 3 | reverse the first 2 | [23, 42, 16, 15, 8, 4] |
| 4 | reverse the last 4 | [23, 42, 4, 8, 15, 16] |
The two tiles at the end came to the front, in their old order.
Input: tiles = [7], k = 1000000000
Output: [7]A row of one tile never changes, however many times the key is pressed.
Input: tiles = [1, 2, 3], k = 3
Output: [1, 2, 3]After 3 presses each tile has gone round once, so the row is as it began.
1 ≤ tiles.length ≤ 100,000 (tiles on the dashboard)0 ≤ tiles[i] ≤ 1,000,000,000 (tile ids)0 ≤ k ≤ 1,000,000,000 (key presses)One key press moves every tile. Pressing it k mod n times costs about n × n moves, which is nearly 10^10 at n = 100,000. And k reaches 10^9, which no loop over the presses can afford. A full turn of n presses restores the row, so only k mod n matters, and the work should be about n.