Problem Link - Implement Stack Using Queue
Problem Statement:
You are tasked with implementing a stack using two queues. The stack should support four operations:
-
push
x
: Pushes element xx to the top of the stack. -
pop: Removes the element on the top of the stack.
-
top: Returns the element on the top of the stack.
-
size: Returns the size of the stack.
Approach:
A stack uses the LIFO principle, while a queue uses FIFO. To simulate a stack with two queues (q1
and q2
):
-
push(
x
): Insert the new element intoq2
, transfer all elements fromq1
toq2
, then swapq1
andq2
soq1
holds the stack. -
pop(): Remove the front of
q1
(the stack’s top). If empty, print an error message. -
top(): Return the front of
q1
. If empty, print an error message. -
size(): Return the number of elements in
q1
.
Time Complexity:
-
push(x): O(n), as all elements from
q1
are moved toq2
. -
pop(): O(1), only the front element is removed.
-
top(): O(1), only the front element is accessed.
-
size(): O(1), size is stored directly.
Space Complexity:
- O(n), since both queues can hold up to
n
elements.