MediumStackDesign

Min Stack

LeetCode
1 approach, code in all languages

Design a stack that supports pushing and popping elements while also being able to report the smallest element it currently holds, with every operation running in constant time.

Implement the MinStack class with the following methods: push(val) adds val to the top of the stack, pop() removes the element on top, top() returns the element on top without removing it, and getMin() returns the minimum element currently in the stack.

Every method must run in O(1) time. The methods top(), pop(), and getMin() will only be called when the stack is non-empty.

Example 1

Input: ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]]

Output: [null,null,null,null,-3,null,0,-2]

After pushing -2, 0, -3, getMin() returns -3. Popping removes -3; top() then returns 0 and getMin() returns -2.

Example 2

Input: ["MinStack","push","push","getMin","pop","getMin"] [[],[5],[3],[],[],[]]

Output: [null,null,null,3,null,5]

With 5 and 3 on the stack, getMin() is 3. After popping 3, the minimum is back to 5.

Constraints

  • -2^31 <= val <= 2^31 - 1
  • Methods pop, top, and getMin are always called on a non-empty stack
  • At most 3 * 10^4 calls will be made to push, pop, top, and getMin
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now