Problem
Design a stack that supports increment operations on its elements.
Implement the CustomStack
class:
CustomStack(int maxSize)
Initializes the object withmaxSize
which is the maximum number of elements in the stack.void push(int x)
Addsx
to the top of the stack if the stack has not reached themaxSize
.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 bottomk
elements of the stack byval
. If there are less thank
elements in the stack, increment all the elements in the stack.
Examples
Example 1:
|
|
Solution
Method 1 - Using an array
We can use array based stack implementation, and handle the increments just by looping till k initial elements.
Code
|
|
|
|
Complexity
- ⏰ Time complexity
push(x)
: O(1) - Adding an element to the stack.pop()
: O(1) - Removing an element from the stack.increment(k, val)
: O(k) - Incrementing the value of the bottomk
elements.
- 🧺 Space complexity:
O(n)
, , where n is themaxSize
of the stack. This accounts for the space used by the singlestack
array.