r/LeetcodeChallenge • • 13d ago

STREAK🔥🔥🔥 LeetCode 155 Min Stack

Post image

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 Upvotes

1 comment sorted by

1

u/nian2326076 13d ago

You're on the right track with the Min Stack problem. Storing the minimum alongside each value means popping the stack won't require recalculating the minimum.

For further practice on stack-related questions, you can use PracHub to tackle similar problems and enhance your understanding of data structures.