Data Structures & AlgorithmsModerateProduct placement · Amazon/Microsoft

A stack is implemented with two queues where push is costly (new element goes into the empty queue, then everything else is moved behind it). What are the costs of push and pop for n elements?

  1. A. push O(1), pop O(1)
  2. B. push O(log n), pop O(log n)
  3. C. push O(n), pop O(1)
  4. D. push O(1), pop O(n)

Correct answer: C. push O(n), pop O(1)

Each push reorders the queue so the newest element is at the front, which moves all n existing elements; pop is then a single dequeue. The alternative design makes pop costly instead.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic