Difficulty: Easy, Asked-in: Facebook, Microsoft, Amazon, Adobe, Goldman Sachs, Morgan Stanley, Walmart.
Key takeaway: An excellent problem to learn use cases of stack and queue operations in problem-solving.
Write a program to implement a queue using two stacks. The implemented queue should support standard enqueue and dequeue operations.
Let's visualise difference between order of elements in stack and queue.
Understanding stack order: Suppose we push 1, 2, 3, 4, 5 into the stack and pop them one by one. The order of popped output will be 5, 4, 3, 2, 1. Here 5 is the last inserted element that is coming first, and 1 is the first inserted element that is coming last.
Understanding queue order: Suppose we enqueue 1, 2, 3, 4, 5 into queue and dequeue them one by one. The order of dequeued output will be 1, 2, 3, 4, 5. Here 5 is the last inserted element that is coming last and 1 is the first inserted element that is coming first.
From above observation, the final stack output (5, 4, 3, 2, 1) is in the reverse order of the final queue output (1, 2, 3, 4, 5). Before popping elements from stack, if we reverse the order of elements, we will get popped output in queue order. So one idea is to keep newly arrived element at the bottom of stack during push operation.
Enqueue operation: We insert new element at the bottom of stack. For this, we use another auxiliary stack to maintain the oder of elements.
Step1: First transfer stack elements to auxiliary stack.
Step 2: Now push new element on top of auxiliary stack.
Step 3: Again transfer all auxiliary stack elements to main stack.
After this process, new element will go to the bottom of the main stack, which will come last during the dequeue operation. In other words, the first inserted element (oldest element) will be on the top of main stack, which will come first during dequeue operation.
Dequeue operation: We simply remove elements from the top of main stack.
Our queue model will use two stacks: one for dequeue operation and two for enqueue operation. Suppose we use mainStack and tempStack to simulate queue process.
If mainStack is empty, throw an empty error and return. Otherwise, pop the top element from mainStack and return it. We also decrement the queue size by 1.
deQueue()
if mainStack is empty
print "Queue is empty!"
return INT_MIN
stackTop = pop the top element from mainStack
queueSize = queueSize - 1
return stackTopConstant number of stack operations will be performed, so time complexity = O(1). We are not using extra space, so space complexity = O(1)
enQueue(x)
while mainStack is not empty
stackTop = pop the top element from mainStack
push stackTop onto tempStack
push x onto tempStack
queueSize = queueSize + 1
while tempStack is not empty
stackTop = pop the top element from tempStack
push stackTop onto mainStackSuppose we have n elements in main stack when new element arrived. So each element except new element is pushed and popped twice, and new element is popped and pushed once.
Total stack operations = Total number of push operations + Total number of pop operations = 2n + 1 + 2n + 1 = 4n + 2. Time complexity = Total stack operations * O(1) = (4n + 2)* O(1) = O(n)
We are using O(n) extra space for tempStack. Space complexity = O(n). Note: It's an exercise for you to design an efficient algorithm for the front() operation.
class QueueUsingStack
private:
queueSize
stacks mainStack and tempStack
constructor
queueSize = 0
enQueue(x)
while mainStack is not empty
stackTop = top element of mainStack
pop mainStack
push stackTop onto tempStack
push x onto tempStack
queueSize = queueSize + 1
while tempStack is not empty
stackTop = top element of tempStack
pop tempStack
push stackTop onto mainStack
deQueue()
if mainStack is empty
print "Queue is empty!"
return INT_MIN
stackTop = top element of mainStack
pop mainStack
queueSize = queueSize - 1
return stackTopAnother implementation idea is to think in reverse way: keep the newest element at the top of the stack and the first inserted element (oldest element) at the bottom.
Here enqueue is simple: add new element to the top of mainStack and increment queue size by 1. Time complexity = O(1) and space complexity = O(1).
For dequeue, we need to remove the bottom element of mainStack.
Case 1 (When tempStack is empty): We pop all elements from mainStack and push them to tempStack, which helps us to store elements of mainStack in reverse order. Now, bottom element of mainStack will be at the top of tempStack. So pop the top element from tempStack to perform dequeue operation.
Case 2 (When tempStack is not empty): There is no need to transfer elements from one stack to another and we just pop the top element of tempStack. When tempStack is empty after sequence of dequeue operations, we follow the same procedure: Transfer data from mainStack to tempStack.
Implementation steps
class QueueUsingStack
private:
queueSize
stacks mainStack and tempStack
constructor
queueSize = 0
enQueue(x)
push x onto mainStack
queueSize = queueSize + 1
deQueue()
if mainStack and tempStack are both empty
print "Queue is empty!"
return INT_MIN
if tempStack is empty
while mainStack is not empty
stackTop = top element of mainStack
pop mainStack
push stackTop onto tempStack
stackTop = top element of tempStack
pop tempStack
queueSize = queueSize - 1
return stackTopWhen tempStack is not empty: Above algorithm performs only one pop operation. So time complexity of dequeue is O(1), which is the best-case scenario.
When tempStack is empty: Above algorithm pop n elements from mainStack, then push n elements to tempStack and finally pop the top element from tempStack (n is the queue size). Total stack operations = n + n + 1 = 2n + 1. So time complexity of dequeue is O(n), which is the worst-case scenario.
In a sequence of dequeue operations, the worst case will not occur frequently: Some dequeue operations will be O(1), and some will be O(n). For example, this is just like the situation of a dynamic array where logn number of insertions takes linear time, and other insertions take constant time.
In above code, dequeue is costly only when tempStack is empty and there is a need for data transfer between mainStack and tempStack. Suppose an ideal picture: There is n number of enqueue followed by n number of dequeue. Total stack operations = Total stack operations for n enqueue + Total stack operations for 1st dequeue + Total stack operations for remaining n - 1 dequeue = n + 2n + 1 + n - 1 = 4n.
For 2n queue operations, the code will perform 4n stack operations. So, on average, each queue operation performs two stack operations. So the average-case time complexity of each queue operation is O(1). Note: When worst cases are very rare compared to best cases, worst-case analysis may not give a clear picture of time complexity. In such situations, average-case analysis will give a better picture.
Enjoy learning, Enjoy Algorithms!