Implement a stack with a maximum size. push(x) adds x if the stack isn't full. pop() removes and returns the top, or -1 if the stack is empty. increment(k, val) adds val to each of the bottom k elements, or to all elements if there are fewer than k. The expected output lists the results of pop.
Before you code
Applying an increment directly costs O(k). Which element is the first to need the increment, and can the rest of the work wait until then?
Hints
- Keep a second array, inc, the same length as the stack, initially zeros.
- increment(k, val) adds val to inc[min(k, size) − 1] only: O(1).
- On pop, return stack[top] + inc[top], and add inc[top] to inc[top − 1] before discarding it, so the pending increment moves down with the stack.
- State the accounting argument: each pending increment is moved at most once per element popped, so every operation is O(1).
Production & complexity notes
When solving Design a stack with increment operation on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Accounting and potential methods to reinforce the underlying pattern.
What it practices
Paying for work lazily, from Accounting and potential methods.