Problem Description
Design a stack that supports the usual push and pop operations along with an increment operation that adds a given value to the bottom k elements. The stack has a maximum size, and if it’s full, push operations should be ignored.
Key Insights
- Use a normal stack data structure to store the elements.
- To perform the increment operation efficiently, avoid iterating over the bottom k elements every time by using a lazy propagation technique.
- Maintain an auxiliary array "increments" to track pending increments for each element.
- When popping an element, propagate its pending increment to the next element in the stack.
Space and Time Complexity
Time Complexity: O(1) per operation (push, pop, inc)
Space Complexity: O(maxSize), to hold the stack and the auxiliary increment array
Solution
We implement the required operations by leveraging two arrays:
- The primary stack to store values.
- An auxiliary "increments" array of the same size as the stack that keeps track of pending increments.
For the increment operation, instead of updating the bottom k elements directly (which would take O(k) time), we add the increment value to the appropriate index in the increments array. When an element is popped, we add its pending increment to it and propagate the pending increment to the next element. This lazy propagation ensures that each operation runs in constant time.