Coding Interview PatternsDesign a Stack With Increment Operation
MediumCustom Data Structures
Design a Stack With Increment Operation
Explanation & Solution
Description
Design a stack that supports push, pop, and an increment operation on the bottom k elements.
Implement a function that processes an array of operations and an array of arguments:
"CustomStack"— Initializes the stack with a max size ofmaxSize."push"— Pushesxonto the stack if its size is less thanmaxSize. Otherwise, do nothing."pop"— Pops and returns the top of the stack, or-1if empty."increment"— Increments the bottomkelements of the stack byval. If fewer thankelements are in the stack, increment all elements.
Input:operations = ["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"], args = [[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]
0
CustomStack
1
push
2
push
3
pop
4
push
5
push
6
push
7
increment
8
increment
9
pop
10
pop
11
pop
12
pop
Output:[null,null,null,2,null,null,null,null,null,103,202,201,-1]
0
null
1
null
2
null
3
2
4
null
5
null
6
null
7
null
8
null
9
103
10
202
11
201
12
-1
Explanation: After pushes of 1,2 we pop 2. Push 2,3,4 (4 is dropped, max=3). increment(5,100) adds 100 to all 3 elements. increment(2,100) adds 100 to bottom 2. Pop returns 3+100=103, then 2+200=202, then 1+200=201. Empty stack returns -1.
Constraints
1 <= maxSize <= 10001 <= x <= 10001 <= k <= 10000 <= val <= 100- At most
1000calls to each operation
Approach
Custom Data Structures pattern
1. Use a Lazy Increment Array
- Maintain a parallel
incarray alongside the stack inc[i]stores the pending increment that should be applied when elementiis popped- This defers the actual addition until pop time — O(1) increment operation
2. Implement Push
- If below
maxSize, pushxto the stack and push0to theincarray
3. Implement Increment
- Instead of updating the bottom
kelements individually, store the increment at index `min(k, size) - 1` - This single write defers updates for all affected elements
4. Implement Pop
- The actual value of the top element is
stack[top] + inc[top] - Before removing, propagate the increment:
inc[top - 1] += inc[top] - This ensures elements below also receive their pending increments when they are later popped
5. Propagation Chain
- The lazy increment cascades down through the stack on each pop
- When an element at index
iis popped, itsinc[i]is added toinc[i-1] - This correctly applies all accumulated increments in O(1) per pop
Key Insight
- Without the lazy approach, increment would be O(k); with it, all operations are O(1)
- The
incarray acts as a difference array — store once, apply on read
Time
O(1) for all operationsSpace
O(maxSize)