Data Structures & AlgorithmsHardAmazon · Microsoft OA

A stack supports push, pop and multipop(k) (pop up to k elements). Starting from empty, what is the worst-case total cost of any sequence of n operations?

  1. A. O(n²), because a single multipop can cost O(n)
  2. B. O(n log n), by the usual amortised bound
  3. C. O(n), since each element is popped at most once after being pushed
  4. D. O(n·k) for the largest k used

Correct answer: C. O(n), since each element is popped at most once after being pushed

Aggregate analysis: total pops (including inside multipop) ≤ total pushes ≤ n, so all operations together cost O(n) even though one multipop can be Θ(n). The potential function 'number of items on the stack' gives the same result.

More Coding Interview Problems questions

Exams that ask this topic