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?
- A. O(n²), because a single multipop can cost O(n)
- B. O(n log n), by the usual amortised bound
- C. O(n), since each element is popped at most once after being pushed
- 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
- A binary counter starts at 0 and is incremented n times; each increment flips trailing 1s to 0 and one 0 to 1. What is the total number of…
- A service must detect whether a dependency graph with 10⁵ modules and 10⁶ edges has a cycle. Which approach is both correct and efficient?
- Shortest paths in a large grid where each move costs either 0 or 1. Which algorithm is the most efficient correct choice?
- You must report the 100 largest values from a stream of 10⁹ integers using about 1 MB of memory. Which approach fits?
- Edge case: JavaScript type coercion. javascript console.log(typeof null, [] + {}, [] == ![], 0.1 + 0.2 === 0.3); What is printed?
- Edge case: += versus + on a list that has another name. python a = [1, 2, 3] b = a a += [4] a = a + [5] print(b, a) What is printed?