Maps app~30 min2s · 256 MBtarget O(n) time, O(capacity) spaceclassic twin: lc-641queues
A navigation app keeps the latest location pings of a trip in a ring of fixed size, so that its memory never grows. A new ping can go in at the back, and a ping that arrives late and out of order can go in at the front.
The app also drops pings from either end, and reads the ping at either end. The ring never holds more than its capacity, and every command must take constant time, even when the ring has 100,000 slots.
Write run_ring(capacity, commands, values).
capacity pings. Run the commands in order. values[i] is the ping of an add command and is ignored by the others.addfront and addback put the ping at the front or at the back, and answer 1. If the ring is full they change nothing and answer 0.dropfront and dropback remove the ping at the front or at the back and answer 1. If the ring is empty they answer 0.front and back answer the ping at that end, or -1 if the ring is empty.empty answers 1 if the ring holds no ping, else 0. full answers 1 if it holds capacity pings, else 0.Input: capacity = 3, commands = ["addback", "addback", "addfront", "addfront", "back", "front", "dropfront", "full", "addfront", "dropback", "back", "empty"], values = [1, 2, 3, 4, 0, 0, 0, 0, 5, 0, 0, 0]
Output: [1, 1, 1, 0, 2, 3, 1, 0, 1, 1, 1, 0]The ring has three slots. The head is the slot of the front ping, and size counts the pings.
| Command | head |
size |
Slots 0, 1, 2 | Answer |
|---|---|---|---|---|
addback 1 |
0 | 1 | 1, ., . | 1 |
addback 2 |
0 | 2 | 1, 2, . | 1 |
addfront 3 |
2 | 3 | 1, 2, 3 | 1 |
addfront 4 |
2 | 3 | 1, 2, 3 | 0 (full) |
back |
2 | 3 | 1, 2, 3 | 2 |
front |
2 | 3 | 1, 2, 3 | 3 |
dropfront |
0 | 2 | 1, 2, 3 | 1 |
full |
0 | 2 | 1, 2, 3 | 0 |
addfront 5 |
2 | 3 | 1, 2, 5 | 1 |
dropback |
2 | 2 | 1, 2, 5 | 1 |
back |
2 | 2 | 1, 2, 5 | 1 |
empty |
2 | 2 | 1, 2, 5 | 0 |
The front ping 3 sits in slot 2, because adding at the front moved the head back from slot 0 around to the end.
Input: capacity = 1, commands = ["addfront", "full", "addback", "dropback", "empty"], values = [7, 0, 8, 0, 0]
Output: [1, 1, 0, 1, 1]A ring of one slot is full after one ping, so addback fails.
Input: capacity = 2, commands = ["front", "back", "dropfront", "dropback", "empty"], values = [0, 0, 0, 0, 0]
Output: [-1, -1, 0, 0, 1]Every command on an empty ring either answers -1 or 0, and empty answers 1.
1 ≤ capacity ≤ 100,0001 ≤ len(commands) = len(values) ≤ 100,000addfront, addback, dropfront, dropback, front, back, empty and full0 ≤ values[i] ≤ 10^6If an add at the front shifts every ping by one place, a command costs up to 100,000 steps, and 100,000 commands cost 10 billion.
A ring needs no shifting. The front and the back are found from a head slot and a size. Every command takes a few steps, and all commands together take about 100,000 steps.