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()→ Returnstrueif the queue is empty, elsefalse.
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
dequeueorpeekon an empty queue should throw an error or return a clear indicator likenull. - Support both integer and string data types as queue elements.
Companies:
stripe
paypal
flipkart
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
