FastPrepConstant-Time Minimum Stack

Constant-Time Minimum Stack

LinkedIn logoLinkedIn● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

Implement a stack that supports pushing, popping, reading the top value, and retrieving the minimum value, each in O(1) time.

For this exercise, process a finite list of valid operation strings in order, starting with an empty stack:

  • PUSH x: place integer x on top.
  • POP: remove the top value and produce no output.
  • TOP: append the top value to the result without modifying the stack.
  • MIN: append the smallest value currently in the stack to the result without modifying the stack.

Return the integer results of only TOP and MIN, in operation order. Preserve repeated values as separate stack entries. Every POP, TOP, and MIN is guaranteed to occur while the stack is nonempty. If there are no query operations, return an empty array.

Function

runMinStack(operations: String[]) → int[]

Examples

Example 1

operations = ["PUSH -2","PUSH 0","PUSH -3","MIN","POP","TOP","MIN"]return = [-3,0,-2]

The first minimum is -3. After popping it, the top is 0 and the minimum among the remaining values is -2.

Example 2

operations = []return = []

No operations produce no query results.

Example 3

operations = ["PUSH 5","PUSH 5","MIN","POP","MIN"]return = [5,5]

Popping one occurrence of 5 leaves the other occurrence, so both minimum queries return 5.

Constraints

  • For this exercise, assume 0 <= operations.length <= 1000.
  • Every operation is exactly PUSH x, POP, TOP, or MIN; PUSH uses one space and a base-10 integer without a leading plus sign.
  • -10^9 <= x <= 10^9.
  • Every non-push operation has a nonempty stack. The whole sequence must run in O(m) time for m operations, with O(1) work per operation after allocating storage.

More LinkedIn problems

See LinkedIn hiring insights
public int[] runMinStack(String[] operations) {
    // Write your code here.
}
operations["PUSH -2","PUSH 0","PUSH -3","MIN","POP","TOP","MIN"]
expected[-3,0,-2]
Checking account…