Question presented to candidate: "What is a monotonic stack? Explain it, tell me which kinds of problems it solves, and code a Python example such as next greater element, explaining why it is O(n)."
What a strong answer should cover:
- A stack kept sorted (increasing or decreasing) by popping before each push; popped elements get their answer from the new element.
- The four variants: next or previous, greater or smaller, and how strict versus non-strict comparison handles duplicates.
- O(n) time because each index is pushed once and popped at most once, despite the nested loop.
- Recognising the pattern: nearest greater or smaller, spans, histogram rectangle, trapping rain water; and when a heap or monotonic deque fits better.
- Python specifics: a list of indices with
append/pop/[-1],[-1] * nfor defaults,enumerate, andwhile stack and ...relying on short-circuit evaluation.
Code / implementation expected: Yes โ a short Python next-greater (or stock span) function using a list as the stack.