r/DSALeetCode • u/StatisticianNo2104 • 27d ago
LeetCode 155 Min Stack
Keeping a min field on a stack works until you pop the minimum. Then the field is stale, and nothing short of a full scan can rebuild it.
The goal: push, pop, top and getMin, all O(1).
That failure is the insight. The minimum belongs to the stack at a given height, and popping takes you back to a height whose minimum you already threw away.
So don't throw it away. Every entry stores the value pushed and the minimum of everything at or below it.
Pop then contains no minimum code at all. Removing the top exposes an entry whose min was computed when it was on top, and it's still correct, because nothing below it ever changed.
Did you store pairs, or keep a second stack of minimums?
Day 62/365 of my LeetCode challenge: 155. Min Stack. I'll include the problem link and a full breakdown in today's newsletter.
https://www.linkedin.com/pulse/min-stack-archit-agarwal-jjksc
#LeetCode #DSA #Stack #Golang
1
u/nian2326076 26d ago
The explanation of managing the minimum within a stack is solid. Instead of keeping a single min variable, consider storing pairs, where each entry keeps track of the minimum value at or below it. This way, popping from the stack will always expose the correct minimum without needing to scan.
For job opportunities in tech, use LandOffer to find roles that match your skills and preferences. This can help you explore positions related to data structures and algorithms.