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 with maxSize which is the maximum number of elements in the stack.
  • void push(int x) - Adds x to the top of the stack if the stack has not reached the maxSize.
  • int pop() - Pops and returns the top of the stack or -1 if the stack is empty.
  • void inc(int k, int val) - Increments the bottom k elements of the stack by val. If there are less than k elements 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
Custom Stack: Push, Pop, and Increment OperationsInitialAfter push(1), push(2)After pop() → 2After increment(2,100)Empty21-1-101maxSize = 3Stack: [1, 2]Pop returns 2Bottom 2 elements +100Efficient increment operation affects bottom k elementsFinal Output: [2, 101, -1]
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.
Asked in
Amazon 12 Google 8 Microsoft 6 Facebook 4
89.6K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen