Stacks and Queues

Problem shape

Beginner
3
2
1
stack
1
2
3
Core idea

Use one stack for incoming values and one stack for outgoing values.

Step 1 / 5
Problem shape
Current lesson

Queue With Two Stacks Lab

Stacks and Queues Beginner

Queue With Two Stacks

Welcome to the Queue With Two Stacks algorithm lab. Use one stack for incoming values and one stack for outgoing values. Use it when: Use to understand how opposite access patterns can simulate each other. The time complexity is Amortized O(1), and the space complexity is O(n). The pseudocode is: enqueue(x): push x to input dequeue(): if output empty move all input items to output pop output As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

Amortized O(1)

Space

O(n)

Pseudocode

enqueue(x): push x to input
dequeue():
  if output empty
    move all input items to output
  pop output
Open deeper structure lesson
1.0x