Min Stack
Advanced
Min Stack Challenge: Finding the Tinies!
Hello, young Python wizards! Today, your task is to create a special stack that can do magic. This magic stack will keep track of the smallest number. Whenever you add a new number to the stack or take one away, it will always know which number is the smallest! 🧙♂️✨
You'll write a function called min_stack that performs the following actions:
push(x): Add numberxto the stack.pop(): Removes the number on the top of the stack.get_min(): Returns the smallest number in the stack.
Here's how it works:
# Start with an empty stack min_stack(['push', 5]) # Push 5 onto the stack min_stack(['push', 3]) # Push 3 min_stack(['get_min']) # Should return 3 min_stack(['push', 7]) # Push 7 min_stack(['get_min']) # Still should return 3 min_stack(['pop']) # Remove the last element (7) min_stack(['get_min']) # should return 3 min_stack(['pop']) # Remove the last element (3) min_stack(['get_min']) # should return 5
The function will take a command (either push, pop, or get_min) and a number (only if it's a push instruction), and should perform the appropriate stack action and return the result of get_min when requested.
Example Executions:
-
Push and get minimum:
min_stack(['push', 2]) # [2] min_stack(['push', 1]) # [2, 1] min_stack(['get_min']) # returns 1 -
Pop and get minimum:
min_stack(['pop']) # [2] min_stack(['get_min']) # returns 2
Happy coding! Let's find those tiny numbers in your stack!
Inputs
Arg 1:
[["push",5],["push",3],["get_min"],["push",7],["get_min"],["pop"],["get_min"]]Expected Output
[3, 3, 3]Actual Output