64 / 75
E

Implement Stack using Queues

#64
stackqueuedesign

Use one queue: on push, add element then rotate queue size-1 times to move it to front.

Example:

Input:push(1), push(2), top(), pop(), empty()
Output:[null, null, 2, 2, false]

Common Mistakes:

  • Using two queues when one suffices
  • Not rotating queue after push (defeats LIFO purpose)
  • Wrong rotation count (should be size-1, not size)
  • Making pop/top expensive instead of push

Notes:

Push is O(n), pop/top/empty are O(1). Alternative: make push O(1) and pop O(n) using two queues.

64/75
Implement Stack using Queues