
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Min Stack in Python
Here we will see how to make a stack, that can perform push, pop, top, and retrieve the min element in constant time. So the functions will be push(x), pop(), top() and getMin()
To solve this, we will follow these steps −
- Initialize the stack by min element as infinity
- For push operation push(x)
- if x < min, then update min := x,
- push x into stack
- For pop operation pop()
- t := top element
- delete t from stack
- if t is min, then min := top element of the stack
- For top operation top()
- simply return the top element
- for getMin operation getMin()
- return the min element
Example
Let us see the following implementation to get better understanding −
class MinStack(object): min=float('inf') def __init__(self): self.min=float('inf') self.stack = [] def push(self, x): if x<=self.min: self.stack.append(self.min) self.min = x self.stack.append(x) def pop(self): t = self.stack[-1] self.stack.pop() if self.min == t: self.min = self.stack[-1] self.stack.pop() def top(self): return self.stack[-1] def getMin(self): return self.min m = MinStack() m.push(-2) m.push(0) m.push(-3) print(m.getMin()) m.pop() print(m.top()) print(m.getMin())
Input
m = MinStack() m.push(-2) m.push(0) m.push(-3) print(m.getMin()) m.pop() print(m.top()) print(m.getMin())
Output
-3 0 -2
- Related Articles
- max() and min() in Python
- Min Cost Climbing Stairs in Python
- Use of min() and max() in Python
- Explain Stack in Python with examples
- Which is in More Demand: Java Full Stack or Python Full Stack
- Find Min-Max in heterogeneous list in Python
- Python Program for Min Cost Path
- List Methods in Python - in, not in, len(), min(), max()
- Program to fill Min-max game tree in Python
- Program to find maximum subarray min-product in Python
- Stack and Queue in Python using queue Module
- Using List as Stack and Queues in Python
- Python Program to Implement a Stack
- How to get min alphabetical character from the string in Python?
- How to get min, seconds and milliseconds from datetime.now() in Python?

Advertisements