Design a Stack With Increment Operation - Problem
Design a stack that supports increment operations on its elements.
Implement the CustomStack class:
CustomStack(int maxSize)- Initializes the object withmaxSizewhich is the maximum number of elements in the stack.void push(int x)- Addsxto the top of the stack if the stack has not reached themaxSize.int pop()- Pops and returns the top of the stack or-1if the stack is empty.void inc(int k, int val)- Increments the bottomkelements of the stack byval. If there are less thankelements in the stack, increment all the elements in the stack.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["CustomStack","push","push","pop","increment","pop","pop","pop"], values = [[3],[1],[2],[],[2,100],[],[],[]]
›
Output:
[null,null,null,2,null,101,100,-1]
💡 Note:
Create stack with maxSize=3, push 1 and 2, pop returns 2, increment bottom 2 elements by 100, then pop returns 101, 100, and -1 (empty)
Example 2 — Full Stack
$
Input:
operations = ["CustomStack","push","push","push","push"], values = [[2],[1],[2],[3],[4]]
›
Output:
[null,null,null,null,null]
💡 Note:
Stack has maxSize=2, so only first 2 push operations add elements, remaining pushes are ignored
Example 3 — Empty Stack Operations
$
Input:
operations = ["CustomStack","pop","increment"], values = [[1],[],[3,100]]
›
Output:
[null,-1,null]
💡 Note:
Pop from empty stack returns -1, increment on empty stack does nothing
Constraints
- 1 ≤ maxSize ≤ 1000
- 1 ≤ x ≤ 1000
- 1 ≤ k ≤ 1000
- 0 ≤ val ≤ 100
- At most 1000 calls will be made to each method of push, pop and increment.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Sequence of operations: push(1), push(2), pop(), increment(2,100)
2
Process
Stack maintains elements and applies increments efficiently
3
Output
Returns values: [2, 101, 100, -1]
Key Takeaway
🎯 Key Insight: Use lazy propagation to defer increment operations until elements are popped, achieving O(1) time complexity for all operations.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code