KatInterview

Simulate a FIFO Queue with Two Stacks

Stacks & QueuesAuto-graded · 19 test cases
HardAuto-gradedStacks & Queuesstacksqueueamortized-analysis

Last updated

Tests whether you can emulate first-in-first-out ordering using only two LIFO stacks and explain the amortized cost of each operation.

Simulate a FIFO Queue with Two Stacks

You are given a sequence of operations that describe an abstract queue. Your job is to execute each operation in order, using exactly two LIFO stacks as the only internal storage. You may not use a queue, deque, linked list, or any array operation that removes or inserts at the front.

Each operation is encoded as a list of integers:

  • [1, value] — add value to the back of the queue.
  • [2] — remove the value at the front of the queue and record it.
  • [3] — read the value at the front of the queue without removing it, and record it.

Return a list of all recorded values, in the order the corresponding operations were encountered. The input is guaranteed never to issue a remove or read on an empty queue.

Constraints

  • 0 <= len(operations) <= 500_000
  • -1_000_000_000 <= value <= 1_000_000_000 for every add operation.
  • Every operation is one of the three valid forms described above.
  • Target O(1) amortized time per operation and O(q) space for q values currently held in the queue.
  • Allowed stack primitives: append to the end, pop from the end, and read the last element. Front-insertion and front-removal are not permitted.

Examples

Example 1

Input: simulate_queue_with_stacks([[1, 10], [1, 20], [3], [2], [1, 30], [2], [2]])

Output: [10, 10, 20, 30]

Example 2

Input: simulate_queue_with_stacks([])

Output: []

Hints

Hint 1

A single stack reverses the order of whatever you push onto it. What happens to the order if you pour one stack into a second stack?

Hint 2

Keep one stack exclusively for incoming values and one stack exclusively for outgoing values. When should you move elements from one to the other?

Hint 3

Transferring elements between stacks is only safe when the outgoing stack is completely empty. If you transfer at any other time, newer values will jump ahead of older ones and FIFO order breaks. Convince yourself why, then think about what that rule means for the total number of moves each element makes over its lifetime.