Monitoring~12 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-344traversal · two-pointers
A monitoring system keeps a log of deploy ids, oldest first. The incident screen must show the newest deploy first, so the log has to be reversed. The log is large, and the job must reverse it in place, using no second list.
Your team lead has seen two earlier attempts fail on the judge: one with Wrong Answer and one with Time Limit Exceeded. You use a hand trace to find out why, and you write the version that passes.
Write reverse_log(deploy_ids).
deploy_ids[i] is the id of the deploy at place i, oldest first.Input: deploy_ids = [11, 12, 13, 14, 15]
Output: [15, 14, 13, 12, 11]Two places move towards each other, left from the start and right from the end. They swap and stop when they meet.
| Step | left | right | List after the swap |
|---|---|---|---|
| start | 0 | 4 | 11, 12, 13, 14, 15 |
| 1 | 0 | 4 | 15, 12, 13, 14, 11 |
| 2 | 1 | 3 | 15, 14, 13, 12, 11 |
| stop | 2 | 2 | left is not below right: done |
Input: deploy_ids = [7, 8]
Output: [8, 7]One swap reverses two values.
Input: deploy_ids = [42]
Output: [42]One value is already reversed.
0 ≤ deploy_ids.length ≤ 100,000 (deploys in the log)1 ≤ deploy_ids[i] ≤ 1,000,000,000 (deploy ids)Building the reversed list by inserting each id at the front moves every id already placed. That is about n × n / 2 = 5 × 10^9 moves at n = 100,000. Swapping the two ends costs n / 2 swaps in all.