FastPrepCustom Stack with Bottom Increment

Custom Stack with Bottom Increment

Headlands Technologies logoHeadlands Technologies● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Maintain an initially empty stack that can hold at most maxSize integers. Process operations from left to right. Each row describes one operation:

  • [0, x]: push x onto the top if the stack is not full. Otherwise ignore this push.
  • [1]: remove the top element and append its value to the result. If the stack is empty, append -1.
  • [2, k, val]: add val to the bottom min(k, currentSize) elements. If the stack is empty, change nothing.

Return an integer array containing only the pop results, in operation order. Pushes and increments produce no output. A later push starts with its supplied value and must not inherit increments that happened before it was inserted. Do not modify operations.

Implement both a direct increment approach and an approach that handles each operation in constant time by deferring increments.

Function

processCustomStack(maxSize: int, operations: int[][]) → int[]

Examples

Example 1

maxSize = 3operations = [[0,1],[0,2],[1],[0,2],[0,3],[0,4],[2,5,100],[2,2,100],[1],[1],[1],[1]]return = [2,103,202,201,-1]

The push of4 is ignored at capacity. Bottom increments affect only live elements; the pop results are2,103,202,201,-1.

Example 2

maxSize = 2operations = [[2,10,7],[1],[0,5],[2,2,4],[0,8],[1],[1],[1]]return = [-1,8,9,-1]

An increment on the empty stack has no effect. The later pushed8 does not inherit the earlier increment; outputs are-1,8,9,-1.

Example 3

maxSize = 3operations = [[0,10],[0,20],[0,30],[2,2,5],[1],[2,1,7],[1],[1]]return = [30,25,22]

Only the bottom two elements receive5. After popping30, the next increment changes only the bottom element. Outputs are30,25,22.

Constraints

  • 1 <= maxSize <= 1000.
  • 0 <= operations.length <= 3000. There are at most 1000 rows of each operation type.
  • Every row is valid: [0, x] with 1 <= x <= 1000, [1], or [2, k, val] with 1 <= k <= 1000 and 0 <= val <= 100.
  • Every live value is at most 101000, so all values and accumulated increments fit in a signed 32-bit integer.

More Headlands Technologies problems

See Headlands Technologies hiring insights
public int[] processCustomStack(int maxSize, int[][] operations) {
    // write your code here
}
maxSize3
operations[[0,1],[0,2],[1],[0,2],[0,3],[0,4],[2,5,100],[2,2,100],[1],[1],[1],[1]]
expected[2,103,202,201,-1]
Checking account…