TRT
Sign in
mediumExpertLeetCode#lazy propagation#accounting

Design a stack with increment operation

Support push, pop and adding a value to the bottom k elements, all in O(1), by recording increments lazily and passing them down on pop.

The Runtime Theory Team1 min read
Taught inAccounting and potential methodsPro — members onlyThe accounting method overcharges cheap operations and saves the surplus as credit for expensive ones. The potential method does the same with a single function of the structure's state. Both prove amortized bounds when simply adding up costs is hard.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inCustomStack(3), push(1), push(2), pop(), push(2), push(3), push(4), increment(5, 100), increment(2, 100), pop(), pop(), pop(), pop()

out[2, 103, 202, 201, -1]

inCustomStack(2), push(1), increment(1, 5), pop(), pop()

out[6, -1]

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

  1. Keep a second array, inc, the same length as the stack, initially zeros.
  2. increment(k, val) adds val to inc[min(k, size) − 1] only: O(1).
  3. 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.
  4. 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.

Not started

Sign in to save your learning progress.

Sign in to save