Refill only when empty
transcript
An interviewer asks for a queue. You may only use two stacks. One rule decides if it works. Let us find that rule.
Uploads one and two go on the input stack. A read moves both to the output stack. The read answers one. Then upload three arrives. The next read answers two, with no move. Every upload leaves in the order it arrived.
Refilling on every read puts three above two. The answers are one, then three. That is wrong. Refill only when the output stack is empty.
A hundred thousand uploads, then as many reads. Each item moves exactly once across. That is why the whole queue stays fast.
Test an upload, a read, another upload and another read. Also test a read on an empty queue. It answers minus one. Then test many reads in a row, after several uploads.
Move items only if the output is empty. Then every item moves once. Full breakdown in the lecture.