Design a Stack With Increment Operation

Medium

Topics
StackArrayDesign

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

returnsCustomStack(3)push(1)push(2)pop()2push(2)push(3)push(4)increment(5, 100)increment(2, 100)pop()103pop()202… 2 more calls
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

  1. Back the stack with an array; push respects maxSize, pop returns -1 when empty.
  2. Keep a parallel inc array where inc[i] is added when element i is popped, and propagated to inc[i-1].
  3. 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] += val
Asked at Cloudflare
SensAI
Beta
Tap the mic to stop voice mode