DSA AnimatorREVISION VIDEOS
← Back to problems
New

Min Stack — LeetCode 155 video explanation

Design a stack that supports push, pop, top, and get minimum. Every operation must run in constant time.

Loading videos…

DSA Animator › DSA Revision › Stack › Min Stack

Key moments in the Min Stack video

0:03Problem0:10Example0:19Brute force0:28Key idea0:41Dry run0:59Code1:14Takeaway

What you will learn

Remember: store the minimum at every level. Then pops can never lose the previous minimum. The video solves Min Stack (LeetCode 155, Medium) with the Stack Design pattern from the Stack topic, and you can replay every step in the interactive Min Stack animation.

Min Stack video transcript

Problem

Design a stack that supports push, pop, top, and get minimum. Every operation must run in constant time.

Example

Push minus 2, push 0, push minus 3, and get min returns minus 3. Then pop, top returns 0, and get min returns minus 2.

Brute force

Scanning the whole stack for the minimum is O of n per call. Keeping one minimum variable breaks after a pop, because you lose the previous minimum.

Key idea

Keep a second stack of minimums, the same height as the main stack. Each entry is the minimum of everything at or below that level. Push and pop both stacks together, and the minimum is always on top.

Dry run

Push minus 2: the min stack holds minus 2. Push 0: the minimum is still minus 2, so push minus 2 again. Push minus 3: the new minimum is minus 3. Get min reads the top: minus 3. Pop removes minus 3 from both stacks. Top returns 0, and get min now returns minus 2.

Code

In code, push pushes the value, and the smaller of the value and the current minimum. Pop pops both stacks. Top reads the main stack, and get min reads the min stack. Every operation is O of 1 time, with O of n extra space.

Takeaway

Remember: store the minimum at every level. Then pops can never lose the previous minimum.

More Stack revision videos

← All 185 DSA revision videos