Intermediate Level

Implement the minStackFinalMinimum method that simulates stack operations and returns the final minimum value.

You are given two arrays: operation codes and values. Operation 1 means push the matching value, and operation 2 means pop the top value. Values for pop operations can be ignored.

Return the minimum value currently in the stack after all operations. If the stack is empty, return -1.

Example 1
Input:
operations (int[]) = [1,1,1,2]
values (int[]) = [5,3,7,0]
size (int) = 4
Return:
(int) 3
Example 2
Input:
operations (int[]) = [1,1,2,2]
values (int[]) = [4,2,0,0]
size (int) = 4
Return:
(int) -1
Example 3
Input:
operations (int[]) = [1,1,2,1]
values (int[]) = [8,6,0,7]
size (int) = 4
Return:
(int) 7

Maintain two stacks: one for all values and one for current minimum values.

When pushing a value, also push it onto the minimum stack if it is smaller than or equal to the current minimum. When popping, if the removed value equals the top of the minimum stack, pop from the minimum stack too. The current minimum is always available at the top of the minimum stack.

This makes minimum lookup constant time.

Pseudocode:

function minStackFinalMinimum(operations, values, size):
    stack = empty stack
    minStack = empty stack
    for i from 0 to size - 1:
        if operations[i] == 1:
            push values[i] into stack
            if minStack is empty or values[i] <= minStack.top:
                push values[i] into minStack
        else if operations[i] == 2 and stack is not empty:
            removed = pop stack
            if removed == minStack.top:
                pop minStack
    if minStack is empty:
        return -1
    return minStack.top
Run your code to see the result.