#1381
Design a Stack With Increment Operation
MediumArrayStackDesignArrayStack
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
In the optimal approach, we maintain an array for the stack and an auxiliary array to track increments. This allows us to perform the increment operation in constant time, while still keeping track of the actual values in the stack.
⚙️
Algorithm
4 steps- 1Step 1: Initialize an empty list for the stack and an auxiliary list for increments.
- 2Step 2: For push, append the element to the stack and 0 to increments if it hasn't reached maxSize.
- 3Step 3: For pop, return the top element and apply any increment from the auxiliary list.
- 4Step 4: For increment, update the increment array at the index k-1.
solution.py24 lines
1class CustomStack:
2 def __init__(self, maxSize: int):
3 self.stack = []
4 self.increments = [0] * maxSize
5 self.maxSize = maxSize
6
7 def push(self, x: int) -> None:
8 if len(self.stack) < self.maxSize:
9 self.stack.append(x)
10
11 def pop(self) -> int:
12 if not self.stack:
13 return -1
14 index = len(self.stack) - 1
15 increment = self.increments[index]
16 self.increments[index] = 0
17 value = self.stack.pop() + increment
18 if index > 0:
19 self.increments[index - 1] += increment
20 return value
21
22 def inc(self, k: int, val: int) -> None:
23 if k > 0:
24 self.increments[min(k - 1, len(self.stack) - 1)] += valℹ
Complexity note: Push and pop operations are O(1), while increment is O(1) due to the auxiliary array. Overall, space complexity is O(n) due to the storage of the stack and increments.
- 1Using an auxiliary array allows for efficient increment operations.
- 2Understanding the difference between stack size and the number of elements is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.