15% off all plans & roadmaps Use code
See plansDesign a Stack With Increment Operation
- LeetCode 1381
- Medium
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: Build a stack that can add a value to its bottom k elements. Record each bump once at the index where its range ends, and pass it one slot down when the top is popped.
Problem
Design a stack that supports increment operations on its elements.
Implement the CustomStack class:
CustomStack(int maxSize)initializes the object withmaxSize, the largest number of elements the stack can hold.void push(int x)addsxto the top of the stack if the stack has not reachedmaxSize.int pop()removes and returns the top of the stack, or returns-1if the stack is empty.void increment(int k, int val)addsvalto the bottomkelements of the stack. If the stack has fewer thankelements, it addsvalto every element.
Example 1
Input: ["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"] [[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]] Output: [null,null,null,2,null,null,null,null,null,103,202,201,-1] Explanation: CustomStack stk = new CustomStack(3); // Stack is empty [] stk.push(1); // stack becomes [1] stk.push(2); // stack becomes [1, 2] stk.pop(); // returns 2, stack becomes [1] stk.push(2); // stack becomes [1, 2] stk.push(3); // stack becomes [1, 2, 3] stk.push(4); // stack stays [1, 2, 3], since maxSize is 3 stk.increment(5, 100); // stack becomes [101, 102, 103] stk.increment(2, 100); // stack becomes [201, 202, 103] stk.pop(); // returns 103, stack becomes [201, 202] stk.pop(); // returns 202, stack becomes [201] stk.pop(); // returns 201, stack becomes [] stk.pop(); // stack is empty, returns -1
Constraints
1 <= maxSize, x, k <= 10000 <= val <= 100- At most
1000calls will be made to each method ofincrement,pushandpop, each separately.
Constraints that matter
- At most 1000 calls per method with a stack size up to 1000 allows about 10^6 element writes in the brute force. That fits the limit, so the brute force passes, but it is not the design an interviewer wants.
- val is at most 100 and at most 1000 increments run, so any element stays under 101000 before it is popped. A 32-bit int holds that, so you do not need a wider type.
- push must refuse values once the stack is full. The array sizes never grow past maxSize, so memory stays fixed.
- Values are read only at pop time. That lets you defer each increment until a pop needs the value.
Hints
Hint 1
This is a design problem.
Hint 2
Keep the stack as a plain list and do exactly what the statement says.
Solution
Intuition
This is a design problem. The stack state is what you choose, and the question is how increment touches that state. The naive move is to update every affected element right away. The statement does not ask for the values until pop, so eager updates do work nobody reads.
It is like a stack of plates where each sticky note says add to the plates below it. The note stays on the plate where its range ends, and lifting the top plate moves its note down one plate.
The pattern here is lazy propagation. Store each bump once, at the index where its range ends. For an increment on the bottom k elements, that index is min(k, size) - 1.
A bump at index j reaches index j and every index below it. The real value of element i is its stored value plus every bump at index i or higher.
Pop is the only moment a value leaves the stack, so it is the only moment you settle a value. The top element's bump has nowhere else to go, so you add it to the slot below. Every element still in the stack keeps its correct total, and the top leaves with its answer.
Worked example
Input: maxSize = 1. Calls in order: CustomStack(1), pop(), increment(1, 10), push(7), pop(). Output: [null, -1, null, null, 7] Explanation: The stack is empty when pop runs, so it returns -1. The increment call has no element to change. The push stores 7 as the only element, and the final pop returns it. The increment never touched a value, so the 7 comes back unchanged.
Approach 1: Brute force
Keep the stack as a plain list and do exactly what the statement says. push appends when there is room. pop removes the last item. increment loops over the first min(k, size) items and adds val to each one.
This is correct, and it is the first version most people write. Its cost is the loop in increment, which touches up to maxSize items on every call.
Steps
- Create an empty list
itemsand storemaxSizeas the limit. - In push, append x only when the list length is below the limit.
- In pop, return -1 for an empty list. Otherwise remove and return the last item.
- In increment, set limit to min(k, length of items).
- Loop from index 0 to limit - 1 and add val to each item.
Dry run
Trace on the example with maxSize = 1.
- CustomStack(1): items = [], limit = 1.
- pop(): items is empty, so it returns -1.
- increment(1, 10): limit = min(1, 0) = 0. The loop does nothing, and items stays [].
- push(7): length 0 is below 1, so items = [7].
- pop(): removes 7 and returns it.
The outputs are null, -1, null, null, 7, which matches the expected output.
Complexity
| Time | push and pop O(1), increment O(n) worst case |
|---|---|
| Space | O(maxSize) |
Let n be the number of elements in the stack, which never exceeds maxSize. push and pop each do a fixed number of list operations, so each is O(1). increment loops min(k, n) times, one addition per loop, so it costs O(n) in the worst case. The list holds at most maxSize values, which gives O(maxSize) space.
PythonTested in our runner
from typing import List, Optional
class CustomStack:
def __init__(self, maxSize: int):
self.max_size = maxSize
self.items = []
def push(self, x: int) -> None:
if len(self.items) < self.max_size:
self.items.append(x)
def pop(self) -> int:
if not self.items:
return -1
return self.items.pop()
def increment(self, k: int, val: int) -> None:
# Index 0 is the bottom, so the bottom k elements are the first k indices
for i in range(min(k, len(self.items))):
self.items[i] += val
The Design (General/Specific) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Design (General/Specific)
Part of Design Patterns
Approach 2: Lazy increment array (optimal)OptimalDesign (General/Specific)
What is slow in the brute force is the loop in increment. It writes up to maxSize values, but pop reads only one value at a time. Most of those writes are never read, because an element may be popped before anyone looks at it.
The insight that fixes it: a bump on the bottom k elements covers a prefix of the stack. Store that bump once, in a parallel array, at the index where the prefix ends. Pop settles the top element with its bump, then adds that bump to the slot below so the rest of the stack still receives it.
Why it is correct. Keep one invariant: the real value of element i is stack[i] plus the sum of inc[j] for every j at or above i. Pop reads only the top element, and its real value is stack[top] + inc[top]. Moving inc[top] down to the slot below keeps every remaining element's total unchanged, because each one still gets that bump through the slot below it.
Steps
- Keep two lists of equal length:
stackfor values andincfor pending bumps. - In push, if the stack is below maxSize, append x to
stackand append 0 toinc. - In increment, return if the stack is empty. Otherwise add val to inc[min(k, size) - 1].
- In pop, return -1 for an empty stack. Otherwise set top to the last index and result to stack[top] + inc[top].
- If top is above 0, add inc[top] to inc[top - 1].
- Remove the last entry from both lists and return result.
Dry run
Trace on the example with maxSize = 1. Each row shows the state after the call.
| Step | Call | stack | inc | top | returned |
|---|---|---|---|---|---|
| 0 | CustomStack(1) | [] | [] | -1 | null |
| 1 | pop() | [] | [] | -1 | -1 |
| 2 | increment(1, 10) | [] | [] | -1 | null |
| 3 | push(7) | [7] | [0] | 0 | null |
| 4 | pop() | [] | [] | -1 | 7 |
Step 2 returns early because the stack is empty, so no bump is stored. At step 4, top is 0 and the result is 7 + 0 = 7. Since top is 0, there is no slot below to receive a bump. The output is null, -1, null, null, 7, which matches the expected output.
Complexity
| Time | O(1) per call |
|---|---|
| Space | O(maxSize) |
Each method runs a fixed number of list reads, writes and comparisons, with no loop over the stack. So every call is O(1). Each list holds at most maxSize entries, one value and one bump per slot, which gives O(maxSize) space. pop passes a bump down by one index only, so it does not scan the stack.
PythonTested in our runner
from typing import List, Optional
class CustomStack:
def __init__(self, maxSize: int):
self.max_size = maxSize
self.stack = []
self.inc = []
def push(self, x: int) -> None:
if len(self.stack) < self.max_size:
self.stack.append(x)
self.inc.append(0)
def pop(self) -> int:
if not self.stack:
return -1
top = len(self.stack) - 1
result = self.stack[top] + self.inc[top]
if top > 0:
# Pass this element's pending bump down to the slot below
self.inc[top - 1] += self.inc[top]
self.stack.pop()
self.inc.pop()
return result
def increment(self, k: int, val: int) -> None:
if not self.stack:
return
# The bump covers indices 0 through idx, the bottom min(k, size) elements
idx = min(k, len(self.stack)) - 1
self.inc[idx] += val
Common mistakes
- Using
index = k - 1without clamping. If k is 5 and the stack holds 2 items, index 4 sits above the top, so the bump lands in an unused slot. Clamp with min(k, size) - 1 first. - Returning
stack[top]alone in pop. Bumps stored at the top are invisible until you add them, so pop must return stack[top] + inc[top]. - Leaving out the pass-down step. With stack [1, 2] and increment(2, 100), skipping
inc[top - 1] += inc[top]makes pop return 102 and element 1 loses its 100. Add the bump to the slot below before removing the top. - Forgetting
inc[top] = 0in push when the arrays are fixed size. The old bump at that index would carry into the new element. Clear the slot on every push. - Checking
size <= maxSizein push, which allows maxSize + 1 items. The check must be size < maxSize. - Treating index 0 as the top in Python, for example with
items.pop(0). Index 0 is the bottom, and removing from the front costs O(n). Remove from the end with pop() instead.
Edge cases
- Empty stack: pop returns -1, and increment does nothing. Guard the empty case before computing min(k, size) - 1, since that index would be -1.
- maxSize = 1: the first push succeeds, and every later push is ignored until a pop frees the slot.
- k larger than the stack: with stack [1, 2], increment(5, 10) raises both values to 11 and 12. Every element is in the bottom k.
- k = 1: only the bottom element changes. With stack [4, 9], increment(1, 3) gives [7, 9].
- val = 0: the stack does not change, and the call should still be accepted without error.
- Push after an empty stack: the new element starts with no bump, even when an earlier element had one before it was popped.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Design a Stack With Increment Operation, with how to answer them.
Unlock the follow-upsDesign a Stack With Increment Operation FAQ
What is the time complexity of Design a Stack With Increment Operation?
The optimal design runs push, pop and increment in O(1) each. The brute force runs increment in O(n) in the worst case, where n is the current stack size, because it walks the bottom elements.
Why use lazy propagation for Design a Stack With Increment Operation?
Values matter only when they are popped, so writing every bump early wastes work. Lazy propagation stores each bump once, at the index where its range ends. Pop passes it one slot down when the top leaves.
Can Design a Stack With Increment Operation be solved in O(1) extra space?
No, not with this approach. Each slot needs its own pending bump, so the bump array has one entry per stored element. That is O(n) space, but the stack itself already needs O(n) space for the values.
Why does increment need a guard for an empty stack?
With no elements, min(k, size) - 1 is -1, which is not a valid index. Writing to index -1 fails in most languages and can corrupt memory in others. Return early when the stack is empty.
Is there a Python gotcha with this problem?
Yes. Python lists are cheap to append and pop at the end, but insert(0) and pop(0) cost O(n). Keep the top at the end of the list and the bottom at index 0, as the code does.
Asked at
See which companies ask this — Pro
Related problems
- LRU Cache · same technique: Design (General/Specific)
- Min Stack · same technique: Design (General/Specific)
- Time Based Key-Value Store · same technique: Design (General/Specific)
- Encode and Decode Strings · same technique: Design (General/Specific)
- Detect Squares · same technique: Design (General/Specific)
- Design Circular Queue · same technique: Design (General/Specific)
- Find Median from Data Stream · next harder, same pattern
- Implement Trie (Prefix Tree) · same pattern: Design Patterns
- Design Add and Search Words Data Structure · same pattern: Design Patterns
- Extra Characters in a String · same pattern: Design Patterns