Implement a queue data structure given only stacks. What is the time complexity of enqueuing and dequeuing operations?
Anonymous
for simplicity, here is the pseudo code: class queue: instack outstack def enqueue(data): instack.push(data) def dequeue(): if outstack.size() == 0: while instack.size() > 0: outstack.push(instack.pop()) return outstack.pop() def size(): return instack.size()+outstack.size() time complexity for enqueuing is o(1), time complexity for dequeueing is still o(1) when the out stack is not empty, but is o(n) if the out stack is empty. Totally, there will be n times transfer between two stacks, where n is the number of times dequeue() has been called.
Check out your Company Bowl for anonymous work chats.