Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Implement Queue using Stacks

Queuesmedium

Course · Section 11: Working With Arrays · Lecture 149: Simple Array Methods

Implement a FIFO queue using only stack operations (push/pop/peek on arrays). Implement `MyQueue`: - `push(x)` adds to the back. - `pop()` removes and returns the front. - `peek()` returns the front. - `empty()` returns whether the queue is empty.

Examples

Input: push(1), push(2), peek(), pop(), empty()
Output: [1, 1, false]
peek and pop both see 1 (FIFO); the queue still holds 2, so it is not empty.

Sample tests

Input: push(1), push(2), peek(), pop(), empty()
Output: [1,1,false]
Input: drain to empty
Output: true

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Transferring on every operation breaks the amortized O(1) cost.

Learning resources

  • Wikipedia: Queue
Approach & explanation (try first)

Two stacks reverse order twice, restoring FIFO. Each element moves at most once between stacks, giving O(1) amortized operations.

Loading...
⌘/Ctrl + Enter

Run your code to see results.