Design a Stack With Increment Operation

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Design a stack that supports push, pop, and an increment operation on the bottom k elements.

Implement a function that processes an array of operations and an array of arguments:

  • "CustomStack" — Initializes the stack with a max size of maxSize.
  • "push" — Pushes x onto the stack if its size is less than maxSize. Otherwise, do nothing.
  • "pop" — Pops and returns the top of the stack, or -1 if empty.
  • "increment" — Increments the bottom k elements of the stack by val. If fewer than k elements are in the stack, increment all elements.

Examples

Example 1:

Input: operations = ["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"], args = [[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]

Output: [null,null,null,2,null,null,null,null,null,103,202,201,-1]

Explanation: After pushes of 1,2 we pop 2. Push 2,3,4 (4 is dropped, max=3). increment(5,100) adds 100 to all 3 elements. increment(2,100) adds 100 to bottom 2. Pop returns 3+100=103, then 2+200=202, then 1+200=201. Empty stack returns -1.

Example 2:

Input: operations = ["CustomStack","push","push","increment","pop","pop"], args = [[2],[1],[2],[2,10],[],[]]

Output: [null,null,null,null,12,11]

Explanation: Push 1 and 2. increment(2,10) adds 10 to both. Pop returns 12, then 11.

Constraints

  • 1 <= maxSize <= 1000
  • 1 <= x <= 1000
  • 1 <= k <= 1000
  • 0 <= val <= 100
  • At most 1000 calls to each operation
Source: Custom Data Structures pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle