0
0
DSA Pythonprogramming

Implement Stack Using Queue in DSA Python

Choose your learning style9 modes available
Mental Model
Use a queue to act like a stack by rearranging elements so the last added is always at the front.
Analogy: Imagine a line of people where the newest person always moves to the front by asking everyone else to step back, so you can always pick the newest person first.
Queue: front -> [1] -> 2 -> 3 -> rear
Stack: top -> 3 -> 2 -> 1 -> bottom
Dry Run Walkthrough
Input: Push 1, push 2, push 3, then pop once
Goal: Simulate stack push and pop using a single queue so pop returns the last pushed element
Step 1: Push 1 into empty queue
front -> [1] -> rear
Why: First element goes directly into queue
Step 2: Push 2: enqueue 2, then rotate queue to move 2 to front
front -> [2] -> 1 -> rear
Why: Rotate so newest element is at front to simulate stack top
Step 3: Push 3: enqueue 3, then rotate queue to move 3 to front
front -> [3] -> 2 -> 1 -> rear
Why: Newest element must be at front for stack pop
Step 4: Pop: dequeue front element (3)
front -> [2] -> 1 -> rear
Why: Pop returns last pushed element, which is at front
Result:
front -> [2] -> 1 -> rear
Pop returned 3
Annotated Code
DSA Python
from collections import deque

class StackUsingQueue:
    def __init__(self):
        self.queue = deque()

    def push(self, x: int) -> None:
        self.queue.append(x)  # add new element at rear
        # rotate queue to move new element to front
        for _ in range(len(self.queue) - 1):
            self.queue.append(self.queue.popleft())  # move front to rear

    def pop(self) -> int:
        return self.queue.popleft()  # remove front element which is stack top

    def top(self) -> int:
        return self.queue[0]  # front element is stack top

    def empty(self) -> bool:
        return len(self.queue) == 0

# Driver code
stack = StackUsingQueue()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop())  # should print 3
print(stack.top())  # should print 2
print(stack.empty())  # should print False
self.queue.append(x) # add new element at rear
enqueue new element at rear of queue
for _ in range(len(self.queue) - 1): self.queue.append(self.queue.popleft()) # move front to rear
rotate queue to move newly added element to front
return self.queue.popleft() # remove front element which is stack top
pop returns front element which simulates stack top
return self.queue[0] # front element is stack top
top returns front element without removing
OutputSuccess
3 2 False
Complexity Analysis
Time: O(n) for push because we rotate the queue to move new element to front; O(1) for pop and top
Space: O(n) because all elements are stored in the queue
vs Alternative: Naive approach using two queues can have O(1) push but O(n) pop; this approach optimizes pop to O(1) at cost of O(n) push
Edge Cases
Pop or top on empty stack
Raises IndexError because queue is empty
DSA Python
return self.queue.popleft()  # remove front element which is stack top
Push single element then pop
Works normally, pop returns that element
DSA Python
for _ in range(len(self.queue) - 1):
Push duplicate elements
Duplicates are handled normally, order preserved as stack
DSA Python
self.queue.append(x)  # add new element at rear
When to Use This Pattern
When you need to implement a stack but only have a queue available, use queue rotation to simulate stack behavior by keeping the newest element at the front.
Common Mistakes
Mistake: Not rotating the queue after push, so pop returns oldest element instead of newest
Fix: Rotate the queue after each push by moving all elements before the new one to the back
Mistake: Using two queues unnecessarily when one queue with rotation suffices
Fix: Use a single queue and rotate it after push to keep newest element at front
Summary
Implements a stack using a single queue by rotating elements after each push.
Use when only queue data structure is available but stack behavior is needed.
The key insight is to rotate the queue so the newest element is always at the front, simulating stack top.