Data Structures & AlgorithmsHardProduct-company MCQ pattern

A queue is built from two stacks: enqueue pushes onto stack IN; dequeue pops from stack OUT, first moving everything from IN to OUT only when OUT is empty. What is the amortised cost per operation over any sequence of n operations?

  1. A. O(√n)
  2. B. O(n)
  3. C. O(log n)
  4. D. O(1)

Correct answer: D. O(1)

Each element is pushed to IN once, moved to OUT once and popped once, so n operations do O(n) work in total: O(1) amortised. A single dequeue can still cost O(n) in the worst case.

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

Exams that ask this topic