Loading problem...
Design and implement a specialized stack data structure that supports the standard push and pop operations, along with a unique bulk increment operation that modifies elements at the bottom of the stack.
You need to implement the IncrementableStack class with the following methods:
IncrementableStack(int maxCapacity) — Initializes the stack object with a fixed maximum capacity. The stack can hold at most maxCapacity elements at any given time.
void push(int x) — Adds element x onto the top of the stack. If the stack has already reached its maximum capacity, this operation should be ignored and no element should be added.
int pop() — Removes and returns the element at the top of the stack. If the stack is empty, return -1.
void incrementBottom(int count, int delta) — Increases the value of the bottom count elements of the stack by delta. If there are fewer than count elements currently in the stack, increment all existing elements by delta.
Your implementation should efficiently handle all operations, particularly the increment operation which affects multiple elements simultaneously.
["IncrementableStack","push","push","pop","push","push","push","incrementBottom","incrementBottom","pop","pop","pop","pop"]
[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]][null,null,null,2,null,null,null,null,null,103,202,201,-1]IncrementableStack stk = new IncrementableStack(3); // Stack is Empty [] stk.push(1); // stack becomes [1] stk.push(2); // stack becomes [1, 2] stk.pop(); // returns 2 → Top element is 2, stack becomes [1] stk.push(2); // stack becomes [1, 2] stk.push(3); // stack becomes [1, 2, 3] stk.push(4); // stack remains [1, 2, 3] → Capacity reached, push ignored stk.incrementBottom(5, 100); // stack becomes [101, 102, 103] → All 3 elements incremented stk.incrementBottom(2, 100); // stack becomes [201, 202, 103] → Only bottom 2 elements incremented stk.pop(); // returns 103 → Top element is 103, stack becomes [201, 202] stk.pop(); // returns 202 → Top element is 202, stack becomes [201] stk.pop(); // returns 201 → Top element is 201, stack becomes [] stk.pop(); // returns -1 → Stack is empty
["IncrementableStack","push","push","push","pop","pop","pop","pop"]
[[5],[10],[20],[30],[],[],[],[]][null,null,null,null,30,20,10,-1]A stack with capacity 5 is created. Three elements (10, 20, 30) are pushed. When popped in order, they return 30, 20, 10 (LIFO order). The last pop from an empty stack returns -1.
["IncrementableStack","push","push","push","incrementBottom","pop","pop","pop"]
[[3],[1],[2],[3],[2,10],[],[],[]][null,null,null,null,null,3,12,11]Stack is initialized with capacity 3. After pushing 1, 2, 3, the stack is [1, 2, 3]. The incrementBottom(2, 10) operation adds 10 to the bottom 2 elements, making the stack [11, 12, 3]. Popping returns 3, then 12, then 11.
Constraints