Chat app~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-1089read-write-pointers
The preview strip of a chat app has a fixed number of slots. Each slot holds a message id, and a blank slot is marked with 0.
To make blanks visible, the strip shows every blank twice. The other slots move right to make room, and anything pushed past the last slot is dropped. The strip has memory for its slots only, so the edit happens in the slots.
Write double_blanks(slots).
slots[i] is a message id, or 0 for a blank slot.slots in place and return it.Input: slots = [1, 0, 2, 3, 0, 4, 5, 0]
Output: [1, 0, 0, 2, 3, 0, 0, 4]Count the blanks (3), then read from the back and write from the back. The write place starts 3 places beyond the end.
| Read place | Entry | Written to | List after |
|---|---|---|---|
| 7 | 0 | places 10 and 9: outside, dropped | [1, 0, 2, 3, 0, 4, 5, 0] |
| 6 | 5 | place 8: outside, dropped | [1, 0, 2, 3, 0, 4, 5, 0] |
| 5 | 4 | place 7 | [1, 0, 2, 3, 0, 4, 5, 4] |
| 4 | 0 | places 6 and 5 | [1, 0, 2, 3, 0, 0, 0, 4] |
| 3 | 3 | place 4 | [1, 0, 2, 3, 3, 0, 0, 4] |
| 2 | 2 | place 3 | [1, 0, 2, 2, 3, 0, 0, 4] |
| 1 | 0 | places 2 and 1 | [1, 0, 0, 2, 3, 0, 0, 4] |
| 0 | 1 | place 0 | [1, 0, 0, 2, 3, 0, 0, 4] |
Input: slots = [0]
Output: [0]The second 0 would be past the end, so it is dropped.
Input: slots = [4, 5, 6]
Output: [4, 5, 6]Nothing to double, so nothing moves.
1 ≤ slots.length ≤ 100,000 (slots in the strip)0 ≤ slots[i] ≤ 1,000,000,000 (message ids, 0 for a blank)A strip can have up to 50,000 blanks among 100,000 slots. Shifting the tail right for each blank costs up to n moves, so up to n × n / 4 moves in all: 2.5 × 10^9 at n = 100,000. Reading and writing from the back puts each entry in its place once.