Social feed~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-232stacks
A social feed app uploads photos one at a time. A photo must go out in the order it was added: the oldest waiting photo goes first. An old code library offers only stack tools: add to the top, take from the top, and look at the top.
You must build the first-in, first-out waiting line from two such stacks. The app may add and read 100,000 times a day, so every photo should be moved only a few times in total.
Write run_queue(commands, values).
values[i] is the photo number of a push, and is ignored by the other commands.push adds a photo at the back of the line. It gives no answer.pop removes the oldest photo and answers its number, or -1 if the line is empty.peek answers the number of the oldest photo without removing it, or -1 if the line is empty.empty answers 1 if the line holds no photo, else 0.pop, peek and empty commands, in order.Input: commands = ["push", "push", "peek", "pop", "push", "pop", "pop", "pop", "empty"], values = [1, 2, 0, 0, 3, 0, 0, 0, 0]
Output: [1, 1, 2, 3, -1, 1]Photos wait in the incoming stack. When the oldest is needed and outgoing is empty, every photo moves over, one by one, which reverses their order.
| Command | incoming (top at the right) |
outgoing (top at the right) |
Answer |
|---|---|---|---|
push 1 |
1 | ||
push 2 |
1, 2 | ||
peek |
2, 1 | 1 | |
pop |
2 | 1 | |
push 3 |
3 | 2 | |
pop |
3 | 2 | |
pop |
3 | ||
pop |
-1 | ||
empty |
1 |
The second pop takes photo 2 from the top of outgoing. Photo 3 waits in incoming behind it, as it should.
Input: commands = ["pop", "peek", "empty"], values = [0, 0, 0]
Output: [-1, -1, 1]Nothing has been pushed, so both reads answer -1, and the line is empty.
Input: commands = ["push", "peek", "empty", "pop", "empty"], values = [9, 0, 0, 0, 0]
Output: [9, 0, 9, 1]After the peek, photo 9 sits in outgoing, so the line is not empty. Both stacks must be checked.
1 ≤ len(commands) = len(values) ≤ 100,000push, pop, peek or empty0 ≤ values[i] ≤ 10^6Moving every photo to a second stack and back on each read costs about twice the length of the line. With 50,000 photos waiting and 50,000 reads, that is about 5 billion moves.
A photo moves from incoming to outgoing once, and leaves from outgoing once. That is at most 2 moves for each photo, so about 200,000 steps for the whole day.