Data Structures & AlgorithmsVery hardCAT · GATE CS

Problem: Which best explains why a monotonic stack is the standard technique for the 'next greater element' problem, giving O(n) overall time?

  1. A. It relies on the input being sorted first
  2. B. Each element is pushed and popped from the stack at most once across the whole scan, so total stack operations are O(n) even though there's a nested-looking while loop
  3. C. It needs a separate O(n) pass per element, giving O(n^2) total
  4. D. The stack always has size 1, so each operation is O(1) trivially

Correct answer: B. Each element is pushed and popped from the stack at most once across the whole scan, so total stack operations are O(n) even though there's a nested-looking while loop

Although there is a while loop inside the main loop, amortized analysis shows each element enters and leaves the stack exactly once, so the total number of push/pop operations across the whole array is O(n), not O(n^2).

More Coding Interview Problems questions

Exams that ask this topic