Design a Stack With Increment Operation
Medium
Topics
Design a stack with a bulk-increment operation. Implement CustomStack(maxSize) and: push(x) (adds x only if the stack size is less than maxSize), pop() (removes and returns the top element, or -1 if empty), and increment(k, val) (adds val to the bottom k elements — or all of them if the stack has fewer than k).
Example 1
A stack with a maximum size and one unusual operation:
increment(k, val) adds val to the bottom-most k elements, or to all of them if there are fewer than k. A push beyond the maximum is ignored rather than refused, and a pop from an empty stack answers -1.Calls run top to bottom; the arrow shows what each one returns.
Input: operations = ["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"], values = [[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]] Output: [null,null,null,2,null,null,null,null,null,103,202,201,-1]
Constraints
- 1 <= maxSize <= 1000
- 1 <= x, val <= 100
- 0 <= k <= 1000
- At most 1000 calls.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A plain array is the stack. The only twist is increment: naively adding val to k elements is O(k), but you can defer it with a lazy increment array so each op is O(1).
Approach
- Back the stack with an array; push respects maxSize, pop returns -1 when empty.
- Keep a parallel
incarray where inc[i] is added when element i is popped, and propagated to inc[i-1]. - increment(k, val) just adds val to inc[min(k, size) - 1] — the bottom k elements inherit it on the way out.
Dry Run
CustomStack(3). `pending[i]` is an increment owed to everything at depth i and
below, applied lazily on the way out.
push 1 stack [1] pending [0]
push 2 stack [1, 2] pending [0, 0]
pop -> 2 stack [1] pending [0]
push 2 stack [1, 2] pending [0, 0]
push 3 stack [1, 2, 3] pending [0, 0, 0]
push 4 stack [1, 2, 3] pending [0, 0, 0] -- refused, maxSize is 3
increment 5 100 pending [0, 0, 100] k=5 clamped to depth 2
increment 2 100 pending [0, 100, 100]
pop -> 103 3 + pending[2] = 103; pending[1] += 100 -> 200
stack [1, 2] pending [0, 200]
pop -> 202 2 + 200 = 202; pending[0] += 200
stack [1] pending [200]
pop -> 201 1 + 200 = 201
pop -> -1 empty
answer null|null|null|2|null|null|null|null|null|103|202|201|-1
The two increments both land on a single slot each, and that is what makes them
O(1) instead of O(k). `increment 5 100` is clamped to the top of the stack at
depth 2; `increment 2 100` records at depth 1. Neither touches more than one
entry.
The debt then flows DOWNWARD on pop: before removing depth i, its pending is
added to depth i - 1. Follow the 100 recorded at depth 2 -- it is paid to the 3,
then passed to depth 1 where it joins the other 100 to make 200, which is then
paid to the 2 and passed down to the 1. Every element ends up with exactly the
increments that were meant for it.
Note the silent refusal at `push 4`. A full stack ignores the push rather than
erroring, and crucially pending is not extended either. Append to pending anyway
and the two arrays desync by one: the three pops return 3, 102, 201 instead of
103, 202, 201, and pending is left holding an orphaned 200.Complexity
- Time — O(1): push, pop, and increment are all constant time with the lazy increment array.
- Space — O(maxSize): the value and increment arrays.
Common Pitfalls
- A direct loop in increment is also accepted but O(k); the lazy array keeps it O(1).
Full Solution — all languages
class CustomStack:
def __init__(self, maxSize):
self.maxSize = maxSize
self.stack = []
# pending[i] is added to everything at or below depth i when it is popped
self.pending = []
def push(self, x):
if len(self.stack) < self.maxSize:
self.stack.append(x)
self.pending.append(0)
def pop(self):
if not self.stack:
return -1
i = len(self.stack) - 1
if i > 0:
self.pending[i - 1] += self.pending[i]
return self.stack.pop() + self.pending.pop()
def increment(self, k, val):
i = min(k, len(self.stack)) - 1
if i >= 0:
self.pending[i] += valimport java.util.*;
class CustomStack {
private final int maxSize;
private final List<Integer> stack = new ArrayList<>();
private final List<Integer> pending = new ArrayList<>();
public CustomStack(int maxSize) {
this.maxSize = maxSize;
}
public void push(int x) {
if (stack.size() < maxSize) {
stack.add(x);
pending.add(0);
}
}
public int pop() {
if (stack.isEmpty()) return -1;
int i = stack.size() - 1;
if (i > 0) pending.set(i - 1, pending.get(i - 1) + pending.get(i));
return stack.remove(i) + pending.remove(i);
}
public void increment(int k, int val) {
int i = Math.min(k, stack.size()) - 1;
if (i >= 0) pending.set(i, pending.get(i) + val);
}
}#include <bits/stdc++.h>
using namespace std;
class CustomStack {
public: CustomStack(int maxSize) : maxSize_(maxSize) {
}
void push(int x) {
if ((int)stack_.size() < maxSize_) {
stack_.push_back(x);
pending_.push_back(0);
}
}
int pop() {
if (stack_.empty()) return -1;
int i = (int)stack_.size() - 1;
if (i > 0) pending_[i - 1] += pending_[i];
int out = stack_.back() + pending_.back();
stack_.pop_back();
pending_.pop_back();
return out;
}
void increment(int k, int val) {
int i = min(k, (int)stack_.size()) - 1;
if (i >= 0) pending_[i] += val;
}
private: int maxSize_;
vector<int> stack_, pending_;
};class CustomStack {
constructor(maxSize) {
this.maxSize = maxSize;
this.stack = [];
this.pending = [];
}
push(x) {
if (this.stack.length < this.maxSize) {
this.stack.push(x);
this.pending.push(0);
}
}
pop() {
if (!this.stack.length) return -1;
const i = this.stack.length - 1;
if (i > 0) this.pending[i - 1] += this.pending[i];
return this.stack.pop() + this.pending.pop();
}
increment(k, val) {
const i = Math.min(k, this.stack.length) - 1;
if (i >= 0) this.pending[i] += val;
}
}
Asked at
Cloudflare