← Oracle questions

Stack using Queue

Filed under Oracle · Also reported at Optum (UnitedHealth Group)

Free read 3 of 3

Verify that only enqueue, dequeue from front, front, and size/is_empty operations are permitted.

The question

Implement a last-in-first-out (LIFO) stack using only standard queue operations. You must support push, pop, top, and empty operations.

Constraints

  • 1 <= Number of calls <= 100
  • -10^9 <= element value <= 10^9
  • All pop and top operations are called on non-empty stacks.

Examples

Input
push(1), push(2), top(), pop(), empty()
Output
[null, null, 2, 2, false]
Why
Pushing 1 then 2 places 2 at the top. top() returns 2, pop() removes 2, and empty() evaluates to false.

Approach

  1. Verify that only enqueue, dequeue from front, front, and size/is_empty operations are permitted.

Solution

O(n) push, O(1) pop/top time; O(n) space

Python
from collections import deque

class MyStack:
    def __init__(self):
        self.q = deque()

    def push(self, x: int) -> None:
        self.q.append(x)
        for _ in range(len(self.q) - 1):
            self.q.append(self.q.popleft())

    def pop(self) -> int:
        return self.q.popleft()

    def top(self) -> int:
        return self.q[0]

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

Tips

  • What they are testing: Tests basic queue manipulation and understanding of LIFO vs FIFO data flows.
  • Common mistake: Failing to rotate the queue elements upon pushing, leading to FIFO order instead of LIFO.

Related Oracle questions

Collected from public candidate posts and coding forums. Updated Nov 2026.