Design a Stack With Increment Operation (LeetCode 1381): Solution and Explanation
Build a stack with a capacity maxSize that supports push, pop (returning -1 when empty), and increment(k, val), which adds val to the bottom k elements, or to all of them if there are fewer than k.
Intuition
The direct version stores the values in an array and loops over the bottom k of them in increment. That is O(k) per call, which is fine for the limits here, but there is a neat way to make every call O(1), and interviewers usually ask for it.
Notice that you never look at an element until it is popped. So increment does not have to change any values right away. It only has to leave a note saying "everything from slot k - 1 downward owes val". Keep those notes in a second array inc, one tag per slot, where inc[i] applies to slot i and every slot below it.
When you pop the top slot, its real value is the raw value plus its own tag, since any tag above it has already been handed down. Before you throw the top tag away, add it to the tag of the slot below, because that slot and everything under it were covered by the same increments.
So a tag slides down one slot at a time as the stack shrinks, which is exactly how many times it is needed, and each operation touches at most two array cells.
Approach: Lazy increment tags
- Store
maxSize, a liststackof raw values, and a parallel listincof tags. push(x): if the stack has fewer thanmaxSizeelements, appendxtostackand 0 toinc.increment(k, val): leti = min(k, size) - 1. Ifi >= 0, addvaltoinc[i].pop(): return -1 if empty. Otherwise letibe the top index. Ifi > 0, addinc[i]toinc[i - 1]. Remove both top entries and returnstack[i] + inc[i].
Step-by-step example
maxSize = 3; push 1, push 2, pop, push 2, push 3, push 4, increment(5,100), increment(2,100), pop x4
- push(1), push(2): stack = [1, 2], inc = [0, 0]. pop(): the top tag is 0, so return 2. Stack = [1].
- push(2), push(3): stack = [1, 2, 3], inc = [0, 0, 0]. push(4) is ignored because 3 slots are used.
- increment(5, 100): min(5, 3) - 1 = 2, so inc = [0, 0, 100]. increment(2, 100): index 1, so inc = [0, 100, 100].
- pop(): hand 100 down so inc[1] = 200, then return 3 + 100 = 103.
- pop(): hand 200 down so inc[0] = 200, then return 2 + 200 = 202.
- pop(): slot 0 has nothing below it, so return 1 + 200 = 201. The last pop finds an empty stack and returns -1.
Code: Python, Java, C++
1class CustomStack:
2 def __init__(self, maxSize: int):
3 self.max_size = maxSize
4 self.stack = []
5 self.inc = []
6
7 def push(self, x: int) -> None:
8 if len(self.stack) < self.max_size:
9 self.stack.append(x)
10 self.inc.append(0)
11
12 def pop(self) -> int:
13 if not self.stack:
14 return -1
15 i = len(self.stack) - 1
16 if i > 0:
17 self.inc[i - 1] += self.inc[i]
18 return self.stack.pop() + self.inc.pop()
19
20 def increment(self, k: int, val: int) -> None:
21 i = min(k, len(self.stack)) - 1
22 if i >= 0:
23 self.inc[i] += val1class CustomStack {
2 private int[] stack;
3 private int[] inc;
4 private int size = 0;
5
6 public CustomStack(int maxSize) {
7 stack = new int[maxSize];
8 inc = new int[maxSize];
9 }
10
11 public void push(int x) {
12 if (size < stack.length) {
13 stack[size] = x;
14 inc[size] = 0;
15 size++;
16 }
17 }
18
19 public int pop() {
20 if (size == 0) {
21 return -1;
22 }
23 int i = size - 1;
24 if (i > 0) {
25 inc[i - 1] += inc[i];
26 }
27 size--;
28 return stack[i] + inc[i];
29 }
30
31 public void increment(int k, int val) {
32 int i = Math.min(k, size) - 1;
33 if (i >= 0) {
34 inc[i] += val;
35 }
36 }
37}1class CustomStack {
2 vector<int> stk;
3 vector<int> inc;
4 int cap;
5
6public:
7 CustomStack(int maxSize) {
8 cap = maxSize;
9 }
10
11 void push(int x) {
12 if ((int) stk.size() < cap) {
13 stk.push_back(x);
14 inc.push_back(0);
15 }
16 }
17
18 int pop() {
19 if (stk.empty()) {
20 return -1;
21 }
22 int i = (int) stk.size() - 1;
23 if (i > 0) {
24 inc[i - 1] += inc[i];
25 }
26 int res = stk[i] + inc[i];
27 stk.pop_back();
28 inc.pop_back();
29 return res;
30 }
31
32 void increment(int k, int val) {
33 int i = min(k, (int) stk.size()) - 1;
34 if (i >= 0) {
35 inc[i] += val;
36 }
37 }
38};Time and space complexity
O(1) per call
push, pop and increment each read or write at most two array cells, no matter how large k is.
O(maxSize)
The value list and the tag list each hold at most maxSize entries.
Other approaches
Loop in increment (time O(1) push and pop, O(k) increment, space O(maxSize))
Keep one array and add val to each of the bottom min(k, size) elements directly. It is simple and passes the given limits, but increment costs O(k).
Difference array over a fixed buffer (time O(1) per call, space O(maxSize))
Preallocate arrays of length maxSize and track the size with a counter instead of appending. It is the same lazy-tag idea, written the way Java and C# usually do it.
Common mistakes
- Forgetting to pass the top tag down on pop. The elements below then lose every increment that was recorded at the top slot.
- Putting the tag at index k - 1 without clamping to the current size. When k is larger than the stack, the tag must go on the top element.
- Pushing past
maxSize. A push on a full stack must do nothing, not grow the stack. - Returning the raw value from pop instead of raw plus the slot's tag.
Frequently asked questions
Why does the tag at slot i cover the slots below it and not above?
increment always affects the bottom k elements, so every increment covers a prefix of the stack. A single tag at the top of that prefix describes it fully, and slots above it are untouched.
Why is it safe to read the top's real value as raw plus only its own tag?
Any tag that sat above the current top was handed down to it when that higher slot was popped. So by the time a slot is on top, its own tag already includes every increment that covered it.
Does pushing a new element after an increment receive the old increment?
No. The new slot starts with a tag of 0, and the old tag sits on a lower slot, so it only applies to elements that existed when increment was called.