Amazon Interview Question
Software Engineer / Developersqueue is FIFO.
insert on top of stack - O(1)
to dequeue - pop all elements in stack - O(n), return last
element popped, push all elements back on stack - O(n)
Queue is First in First Out.
Stack is Last in First Out.
In order to mimic the Queue behavior, we will use two stacks.
Pop() all elements from StackA to StackB one by one - O(n)
Push() new element in StackA, so it stays at the bottom- O(1). Pop() all elements from StackB back to StackA, one by one so that the very first element in StackA would stay on the top- O(n).
2 stacks: one for back_(pop/push) operations and the other one is for front_(pop/push) operations.
- Anonymous November 24, 2010For example, if current operation is front operation (second stack involved) and the last was in back (i.e. on 1st stack) than just pop items from 1st and push to 2nd stack. And vice versa.