Problem 155

Abstract / Summary

Design a stack that supports push pop top and retrieving the minimum element in constant time.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0155.py

class MinStack:

    def __init__(self):
        self.data = []
        self.min  = []

    def push(self, val: int) -> None:
        self.data.append(val)
        lowest = val if not self.min else self.min[-1]
        self.min.append(val if val < lowest else lowest)

    def pop(self) -> None:
        self.data.pop()
        self.min.pop()

    def top(self) -> int:
        return self.data[-1]

    def getMin(self) -> int:
        return self.min[-1]
20 lines | 477 bytes | submitted August 31, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 59% (4+ million submissions).

Typical patterns to solve this problem:
  • Design
  • Stack
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a MinStack class that supports the usual stack operations-push, pop, and top-while also offering constant-time retrieval of the current minimum element. Two internal lists are maintained: one (data) stores the stack’s values in insertion order, and the other (min) mirrors the size of data while keeping track of the smallest value seen up to each position. By updating the auxiliary list on every push and pop, the class guarantees that getMin can return the minimum without scanning the entire stack.

Initialization

When a MinStack instance is created, both internal containers are instantiated as empty Python lists. This establishes a clean state where no elements have been pushed yet.

def __init__(self):
    self.data = []
    self.min  = []

The empty lists also serve as natural guards for edge conditions: attempts to access the top element or the minimum will raise an IndexError if the stack is empty, which aligns with typical stack semantics.

Push Operation

The push method adds a new integer to the stack and simultaneously updates the auxiliary minimum list. First, the value is appended to self.data. Then the method determines the current lowest value: if self.min is empty, the new value itself becomes the baseline; otherwise the last entry in self.min represents the minimum of the stack before the new element. The new entry in self.min is the smaller of the incoming value and this baseline, ensuring that each position in self.min reflects the minimum of the stack up to that depth.

def push(self, val: int) -> None:
    self.data.append(val)
    lowest = val if not self.min else self.min[-1]
    self.min.append(val if val < lowest else lowest)

Edge handling is implicit: when the stack is empty (self.min is falsy), lowest is set to val, so the first entry in self.min correctly records the sole element as the minimum.

Pop Operation

Removing the top element is a symmetric operation. The method discards the last element from both self.data and self.min. Because the auxiliary list always mirrors the size of the primary stack, popping from both lists maintains alignment and guarantees that the next call to getMin will reflect the new minimum after removal.

def pop(self) -> None:
    self.data.pop()
    self.min.pop()

If the stack is empty, invoking pop will raise an IndexError, which is consistent with Python’s list behavior and signals an underflow condition to the caller.

Top Operation

The top method provides read-only access to the most recently pushed value without altering the stack. It simply returns the last element of self.data.

def top(self) -> int:
    return self.data[-1]

Attempting to call top on an empty stack triggers an IndexError, mirroring the behavior of the underlying list and preserving the contract that a top element exists only when the stack contains items.

GetMin Operation

Retrieving the current minimum is a constant-time lookup of the last entry in the auxiliary list. Because self.min stores the minimum value up to each depth, the most recent entry always represents the minimum of the entire stack.

def getMin(self) -> int:
    return self.min[-1]

When the stack is empty, this method raises an IndexError, which aligns with the expectation that a minimum cannot be defined for an empty collection.

Edge Cases Handled

The design gracefully addresses several boundary conditions. Pushing the first element correctly initializes both self.data and self.min with the same value, establishing a valid minimum. Subsequent pushes compare the incoming value against the existing minimum, ensuring that the auxiliary list always holds the correct running minimum. Popping the last element reduces both lists to empty, resetting the stack to its initial state without leaving stale references. Accessor methods (top and getMin) rely on Python’s list indexing semantics, automatically raising exceptions when the stack is empty, which provides clear feedback to the caller.

Performance Optimizations

The primary optimization lies in the use of a parallel auxiliary stack (self.min). By storing the minimum at each depth, the implementation avoids any need to traverse self.data when answering a minimum query. This yields constant-time performance for push, pop, top, and getMin. The auxiliary list also grows and shrinks in lockstep with the main stack, eliminating the overhead of additional bookkeeping structures. Because both lists are native Python arrays, appends and pops execute in amortized constant time, leveraging the underlying dynamic array implementation for efficient memory management.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a special stack of toy blocks where each block is numbered. The first part sets everything up by creating two empty boxes to hold the information. One box keeps track of all the blocks stacked up, while the other box stays super focused on remembering the smallest number added so far.

When a new block is added, it goes onto the main stack. Then, the code plays a little game of comparison. It looks at the new number and the smallest number known before and picks the smaller of the two to save in the second box.

Taking a block away is simple. Both boxes say goodbye to their most recent entry at the exact same time so they always match up.

To peek at the very top block of the stack, the code just looks at the last item sitting in the first box. If the goal is to see the smallest number currently in the collection, the code peeks at the last item stored in that special second box that remembers the tiny numbers.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.04 | σ = 0.79

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python C# Rust JS Go TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Java
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Java
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
63 links | 46 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Design Min Stack - Amazon Interview Question - Leetcode 155 - Python'
NeetCode 9 mins
Design Min Stack - Amazon Interview Question - Leetcode 155 - Python
YouTube video 'Min Stack - Leetcode 155 - Stacks (Python)'
Greg Hogg 9 mins
Min Stack - Leetcode 155 - Stacks (Python)
YouTube video 'LeetCode 155: Min Stack'
Engineering Digest 10 mins
LeetCode 155: Min Stack
YouTube video 'min stack | min stack leetcode | leetcode 155 | 2 stacl | 1 stack | no stack solutions'
Naresh Gupta 16 mins
min stack | min stack leetcode | leetcode 155 | 2 stacl | 1 stack | no stack solutions
YouTube video '[Java] Leetcode 155. Min Stack [Stack & Queue #4]'
Eric Programming 7 mins
[Java] Leetcode 155. Min Stack [Stack & Queue #4]
YouTube video 'Leetcode 155: Min Stack Explained in Telugu | Two Stack & Single Stack Approach | srkcodes'
Srk Codes 16 mins
Leetcode 155: Min Stack Explained in Telugu | Two Stack & Single Stack Approach | srkcodes
YouTube video 'LeetCode 155 - Min Stack (JavaScript)'
Hayk Simonyan 5 mins
LeetCode 155 - Min Stack (JavaScript)
YouTube video 'Min Stack | Leetcode 155 | Live coding session 🔥🔥🔥'
Coding Decoded 6 mins
Min Stack | Leetcode 155 | Live coding session 🔥🔥🔥
YouTube video 'Min Stack | LeetCode 155 | Theory + Python code'
Sai Anish Malla 10 mins
Min Stack | LeetCode 155 | Theory + Python code
YouTube video '155. Min Stack || NEETCODE 150'
TechWithSaumya 15 mins
155. Min Stack || NEETCODE 150
YouTube video 'Min Stack - LeetCode #155 - C++'
Sean Chuah 5 mins
Min Stack - LeetCode #155 - C++
YouTube video 'Min Stack || Stack 7|| Placement Preparation Series || Medium || Better|| Optimized||LeetCode 155 ||'
Bro Coders 20 mins
Min Stack || Stack 7|| Placement Preparation Series || Medium || Better|| Optimized||LeetCode 155 ||
YouTube video 'Can You Find Minimum in Stack? (LeetCode 155: Min Stack)'
Code With Zi 8 mins
Can You Find Minimum in Stack? (LeetCode 155: Min Stack)
YouTube video 'Two Stacks, Zero Scans — Min Stack Explained | LeetCode 155'
Code With K5KC 6 mins
Two Stacks, Zero Scans — Min Stack Explained | LeetCode 155
YouTube video '155. Min Stack | Leetcode | Stack | DSA'
Coding with Tamilarasan 14 mins
155. Min Stack | Leetcode | Stack | DSA
YouTube video '155. Min Stack | Leetcode | Easy | cpp | java | python | javascript'
Komal Pal 14 mins
155. Min Stack | Leetcode | Easy | cpp | java | python | javascript
YouTube video 'Daily Leetcode #573: Oct 25, 2021 - 155. Min Stack'
Programming Live with Larry 8 mins
Daily Leetcode #573: Oct 25, 2021 - 155. Min Stack
YouTube video '155. Min Stack | Leetcode | Neetcode | @ShubhamChhimpa'
Shubham Chhimpa 7 mins
155. Min Stack | Leetcode | Neetcode | @ShubhamChhimpa
YouTube video '21. Leetcode 155. Min Stack : Javascript'
Web Fusion with Bharadwaj 29 mins
21. Leetcode 155. Min Stack : Javascript
YouTube video 'Leetcode 155. Min Stack | Design Stack with O(1) Min | Python Solution'
StatLearn Tech 13 mins
Leetcode 155. Min Stack | Design Stack with O(1) Min | Python Solution
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

27 solutions   August 31, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality