Facebook Pixel

Implement a Queue using Stack

JavaScript
hard
30 mins

A queue is a First-In-First-Out (FIFO) data structure. In this problem, you are to simulate a queue using only stacks (which are Last-In-First-Out, LIFO). Your task is to implement the enqueue, dequeue, and peek methods using stack operations.

  • enqueue(value) → Adds an element to the end of the queue.
  • dequeue() → Removes and returns the element from the front of the queue.
  • peek() → Returns the element at the front without removing it.
  • isEmpty() → Returns true if the queue is empty, else false.

Example Inputs & Outputs

const q = new QueueUsingStack(); q.enqueue(1); q.enqueue(2); q.enqueue(3); q.dequeue(); // Output: 1 q.peek(); // Output: 2 q.isEmpty(); // Output: false

Constraints & Edge Cases

  • Only standard stack operations (push, pop, peek, length) are allowed.
  • All operations should have amortized O(1) time complexity.
  • Calling dequeue or peek on an empty queue should throw an error or return a clear indicator like null.
  • Support both integer and string data types as queue elements.

Companies:

stripe
paypal
flipkart

Solve Similar questions 🔥

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.