Implement Queue using Stacks

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2021-10-23

Problem Statement

Design and implement a Queue (FIFO: First-In-First-Out) data structure using only two Stacks (LIFO: Last-In-First-Out) as the underlying storage.


Functional Requirements (FR)


1.Implement a class QueueUsingStacks that supports:
•enqueue(x) → Add an element to the queue.
•dequeue() → Remove and return the front element.
•peek() → Return the front element without removing it.
•isEmpty() → Check if the queue is empty.
•size() → Return the number of elements in the queue.
2.Queue must follow FIFO order, even though stacks follow LIFO order.
3.Both amortized O(1) operations (efficient approach) and naive O(n) approaches can be considered.


Constraints


•Use only stacks (no arrays, lists, or queues directly).
•Should handle large number of enqueue/dequeue operations efficiently.
•Must handle edge cases (e.g., dequeue on empty queue).


Design Details


•Maintain two stacks:
•stackEnqueue → for incoming elements.
•stackDequeue → for outgoing elements.
•When dequeue is called and stackDequeue is empty → move all elements from stackEnqueue to stackDequeue.


Example

1 2QueueUsingStacks q = new QueueUsingStacks(); 3q.enqueue(10); 4q.enqueue(20); 5q.enqueue(30); 6q.dequeue(); // returns 10 7q.peek(); // returns 20 8q.dequeue(); // returns 20


Evaluation Criteria


•Correctness of FIFO behavior.
•Time complexity analysis (amortized O(1) for enqueue/dequeue).
•Handling of edge cases.
•Clean OOP design and method signatures.


Solution

Comments