Monitoring~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-27read-write-pointers · two-pointers
A monitoring agent runs on every server. It collects recent log lines in a fixed buffer of line codes, in the order they were written, and ships the buffer to the central store.
Every few seconds the agent also writes a heartbeat line, code 0, to show that it is alive. Heartbeats carry no information once the buffer is shipped. You see that on quiet servers most of each buffer is heartbeats.
So before shipping, the agent removes the heartbeats. It has no memory to spare for a second buffer, so it edits the buffer in place. The other lines must keep their order.
Write compact(lines).
lines[i] is the code of the line at position i of the buffer, in order. Code 0 is a heartbeat.[].lines in place with O(1) extra memory, then return the kept prefix. The judge checks only the list you return.Input: lines = [210, 0, 0, 404, 0, 503]
Output: [210, 404, 503]| read | lines[read] | What happens | write after | Kept prefix |
|---|---|---|---|---|
| 0 | 210 | kept: copied to position 0 | 1 | 210 |
| 1 | 0 | heartbeat: skipped | 1 | 210 |
| 2 | 0 | heartbeat: skipped | 1 | 210 |
| 3 | 404 | kept: copied to position 1 | 2 | 210, 404 |
| 4 | 0 | heartbeat: skipped | 2 | 210, 404 |
| 5 | 503 | kept: copied to position 2 | 3 | 210, 404, 503 |
After the pass the buffer holds [210, 404, 503, 404, 0, 503]. Only the first 3 positions are the answer.
Input: lines = [0, 0, 0]
Output: []Every line is a heartbeat, so nothing is kept.
Input: lines = [17, 17, 3]
Output: [17, 17, 3]No heartbeats. A code that repeats is still a real line, so both copies of 17 stay.
1 ≤ lines.length ≤ 10^50 ≤ lines[i] ≤ 10^6Deleting one heartbeat from a fixed buffer means shifting every later line one place left. When almost every line is a heartbeat, that is about n^2 / 2 moves: about 5 × 10^9 at n = 10^5. Aim for O(n).
The statement also asks for O(1) extra memory. So you cannot copy the kept lines into a second list as you go. Two positions in the same buffer are enough.