Design a Stack With Increment Operation

Design a stack with a size limit that can also add a value to its bottom elements. - `CustomStack(int maxSize)` creates an empty stack that can hold at most `maxSize` elements. - `void push(int x)` pushes `x` on top if the stack has fewer than `maxSize` elements; otherwise it does nothing. - `int pop()` removes and returns the top element, or returns -1 if the stack is empty. - `void increment(int k, int val)` adds `val` to each of the bottom `k` elements. If there are fewer than `k` elements, it adds `val` to all of them.

30:00

Design a Stack With Increment Operation
medium
Free written solution
Topics
Companies

Design a stack with a size limit that can also add a value to its bottom elements.

  • CustomStack(int maxSize) creates an empty stack that can hold at most maxSize elements.
  • void push(int x) pushes x on top if the stack has fewer than maxSize elements; otherwise it does nothing.
  • int pop() removes and returns the top element, or returns -1 if the stack is empty.
  • void increment(int k, int val) adds val to each of the bottom k elements. If there are fewer than k elements, it adds val to all of them.
Example 1:
Input: {"commands":["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"],"values":[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]}
Output: [null,null,null,2,null,null,null,null,null,103,202,201,-1]
Constraints:
  • 1≤maxSize,x,k≤10001 \leq \text{maxSize}, x, k \leq 1000

  • 0≤val≤1000 \leq \text{val} \leq 100

  • At most 1000 calls are made to each of increment, push and pop.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"],"values":[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]}
new(3)
push(1)
push(2)
pop()
push(2)
push(3)
push(4)
increment(5,100)
increment(2,100)

…

Empty stack with room for 3. Next to each slot we will keep a lazy tag inc[i] meaning "add this to slot i and everything below it".

stack (0/3 used), top first

slot

raw value

tag inc[i]

real

1

free

0

free

real value = raw + every tag at or above that slot; a popped tag is handed to the slot below

Returned values

[null]
Variables
VariableValue
maxSize3
DepthFunction Call
Stack empty
0/16