MediumStackDesignArray

Design a Stack With Increment Operation

LeetCode
1 approach, code in all languages

Design a stack of bounded capacity that, in addition to the usual push and pop, supports a bulk increment on its oldest elements.

Implement the CustomStack class: the constructor takes maxSize and creates an empty stack that can hold at most maxSize elements. push(x) adds x to the top only if the stack has not reached maxSize, otherwise it does nothing. pop() removes and returns the top element, or returns -1 if the stack is empty. increment(k, val) adds val to the bottom k elements of the stack; if there are fewer than k elements, it adds val to all of them.

Aim for an efficient increment that does not touch every affected element on each call.

Example 1

Input: ["CustomStack","push","push","increment","pop","push","pop"] [[3],[1],[2],[5,100],[],[3],[]]

Output: [null,null,null,null,102,null,3]

Push 1 then 2. increment(5,100) adds 100 to all elements (only 2 exist), giving [101,102]. pop() returns 102. Push 3 to get [101,3]. pop() returns 3.

Example 2

Input: ["CustomStack","push","push","push","increment","increment","pop","pop","pop","pop"] [[3],[1],[2],[3],[2,100],[3,10],[],[],[],[]]

Output: [null,null,null,null,null,null,13,112,111,-1]

Stack becomes [1,2,3]. increment(2,100) adds 100 to the bottom 2 giving [101,102,3]; increment(3,10) adds 10 to all three giving [111,112,13]. The pops then return 13, 112, and 111 from the top down, and the final pop on the empty stack returns -1.

Constraints

  • 1 <= maxSize, x, k <= 1000
  • 0 <= val <= 100
  • At most 1000 calls in total will be made to push, pop, and increment
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now