Sponsored
Sponsored
This approach uses a direct array implementation to handle all operations. A list or array is used as the underlying data structure for the stack, and operations are directly performed on the stack as specified. This results in a direct and straightforward implementation, where increment operations iterate over the bottom k elements to increment them by the given value.
Time Complexity: O(k)
for the increment operation, O(1)
for the push and pop operations.
Space Complexity: O(n)
where n
is the max size of the stack.
1class CustomStack {
2 constructor(maxSize) {
3 this.stack = [];
4 this.maxSize = maxSize;
5 }
6
7 push(x) {
8 if (this.stack.length < this.maxSize) {
9 this.stack.push(x);
10 }
11 }
12
13 pop() {
14 if (this.stack.length === 0) {
15 return -1;
16 }
17 return this.stack.pop();
18 }
19
20 increment(k, val) {
21 for (let i = 0; i < Math.min(k, this.stack.length); i++) {
22 this.stack[i] += val;
23 }
24 }
25}
The CustomStack
class in JavaScript uses an array as the underlying storage for the stack. The methods push
, pop
, and increment
are implemented similarly to the Python version, ensuring that operations stay within the maxSize
constraints and using a loop to increment elements.
This approach uses an auxiliary array to optimize the increment operation by storing lazy increments and applying them during the pop operation. This lazy approach ensures that increments do not have to iterate over the stack directly, thus reducing potential redundant operations.
Time Complexity: O(1)
for push and pop; O(1)
amortized for increment.
Space Complexity: O(n)
where n
is the max size of the stack.
1class CustomStack {
2 private int
The Java CustomStack
class uses arrays for both stack
and increment
. Top is an index marker for the top of the stack. Lazy increments are applied when pop
is called using the same logic as in the C++ solution, where each element’s increment value is propagated down as necessary.