Sobes.tech
Junior — Senior

Determining the current minimum in the stack

livecode

Task condition

The stack sequentially contains the elements: 3 4 2 5 1. After that, the methods get_min(), pop(), get_min() and so on are called. It is necessary to analyze the proposed implementation and determine whether the get_min() method will return the correct value after the minimum element has been removed from the stack.

class Stack:
    def __init__(self):
        self.stack = []
        self.min_val_initial = 3

    def push(self, num: int):
        self.stack.append(num)
        self.min_val = min(self.min_val, num)

    def pop(self):
        return self.stack.pop()

    def top(self):
        return self.stack[-1]

    def get_min(self):
        ...

The current code only stores one value of the minimum element (self.min_val) and does not update it when elements are removed from the stack. Therefore, after executing pop(), if the removed element was the minimum, the get_min() method will return an outdated value, which makes its operation incorrect.