Leetcode Top Interview ✨
GithubLinkedinXOfficial Website
  • Leetcode Top Interview 🎯
  • Guide to Calculating Algorithm Complexity 🚀
  • Topic 1 Array - String
    • 88. Merge Sorted Arrays 🧩
    • 27. Remove Element 🧹
    • 26. Remove Duplicates from Sorted Array 🚫
    • 80. Remove Duplicates from Sorted Array II 🚫🚫
    • 169. Majority Element 👑
    • 189. Rotate Array 🔄
    • 121. Best Time to Buy and Sell Stock 📈
    • 122. Best Time to Buy and Sell Stock II 📈💰
    • 55. Jump Game 🏃‍♂️
    • 45. Jump Game II 🏃‍♂️
    • 274. H-Index 📊
    • 380. Insert Delete GetRandom O(1) 🎲
    • 238. Product of Array Except Self 🔄
    • 134. Gas Station ⛽
    • 135. Candy 🍬
    • 42. Trapping Rain Water 🌧️
    • 13. Roman to Integer 🔢
    • 018 Integer to Roman
    • 58. Length of Last Word 🔠
    • 14. Longest Common Prefix 🌱
    • 151. Reverse Words in a String 🔄
    • 6. Zigzag Conversion 🔀
    • 28. Find the Index of the First Occurrence in a String 🔄
    • 68. Text Justification 🔄
  • Topic 2 Two Pointers
    • 125. Valid Palindrome 🚦
    • 392. Is Subsequence 📏
    • 167. Two Sum II - Input Array Is Sorted 🔍
    • 11. Container With Most Water 🏞️
    • 15. 3Sum 🌐
  • Topic 3 Sliding Window
    • 209. Minimum Size Subarray Sum 🌐
    • 3. Longest Substring Without Repeating Characters 🌐
    • 30. Substring with Concatenation of All Words 🌐
    • 76. Minimum Window Substring 🌐
  • Topic 4 Matrix
    • 36. Valid Sudoku 🌐
    • 54. Spiral Matrix 🌐
    • 48. Rotate Image 🔄
    • 73. Set Matrix Zeroes
    • 289. Game of Life 🖼️
  • Topic 5 Hashmap
    • 383. Ransom Note 🔍
    • 205. Isomorphic Strings 🔍
    • 290. Word Pattern 🧩
    • 242. Valid Anagram 🎢
    • 49. Group Anagrams 🤹‍♂️
    • 1. Two Sum 🔍
    • 202. Happy Number 🤩
    • 219. Contains Duplicate II 🔍
    • 128. Longest Consecutive Sequence 🔍
  • Topic 6 Intervals
    • 228. Summary Ranges 📊
    • 56. Merge Intervals 🔀
    • 57. Insert Interval 🆕
    • 452. Minimum Number of Arrows to Burst Balloons 🎈
  • Topic 7 Stack
    • 20. Valid Parentheses 🔍
    • 71. Simplify Path 🗺️
    • 155. Min Stack 🗃️
    • 150. Evaluate Reverse Polish Notation 🧠💻
    • 224. Basic Calculator 🧮
  • Topic 8 Linked List
    • 141. Linked List Cycle 🔁
    • 2. Add Two Numbers 🔢
    • 21. Merge Two Sorted Lists 🔗
    • 138. Copy List with Random Pointer 🔗
    • 92. Reverse Linked List II 🔄
      • Let’s explain step by step 🐇
    • 25. Reverse Nodes in k-Group 🔄
    • 19. Remove Nth Node From End of List 🗑️
    • 82. Remove Duplicates from Sorted List II ❌🔢
    • 61. Rotate List 🔄
    • 86. Partition List 🔗
    • 146. LRU Cache 🔗
  • Topic 9 Binary Tree General
    • 104. Maximum Depth of Binary Tree 🔗
    • 100. Same Tree 🔗
    • 226. Invert Binary Tree 🔗
    • 101. Symmetric Tree 🔗
    • 105. Construct Binary Tree from Preorder and Inorder Traversal 🔗
    • 106. Construct Binary Tree from Inorder and Postorder Traversal 🔗
    • 117. Populating Next Right Pointers in Each Node II 🔗
    • 114. Flatten Binary Tree to Linked List 🔗
    • 112. Path Sum 🔗
    • 129. Sum Root to Leaf Numbers 🔗
      • What_is_DFS
    • 124. Binary Tree Maximum Path Sum 🔗
Powered by GitBook
On this page
  • Problem Statement 📜
  • Examples 🌟
  • Constraints ⚙️
  • Solution 💡
  • Java Solution
  • Explanation of the Solution
  • Time Complexity ⏳
  • Space Complexity 💾

Was this helpful?

  1. Topic 7 Stack

155. Min Stack 🗃️

Previous71. Simplify Path 🗺️Next150. Evaluate Reverse Polish Notation 🧠💻

Last updated 4 months ago

Was this helpful?

Difficulty: Medium - Tags: Stack, Design


Problem Statement 📜

Design a stack that supports the following operations in constant time O(1):

  1. void push(int val): Push the element val onto the stack.

  2. void pop(): Remove the element on the top of the stack.

  3. int top(): Retrieve the top element of the stack.

  4. int getMin(): Retrieve the minimum element in the stack.

You must implement all these methods in constant time.


Examples 🌟

🔹 Example 1:

Input:

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

Output:

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

Explanation:

MinStack minStack = new MinStack();
minStack.push(-2);    // Stack: [-2]
minStack.push(0);     // Stack: [-2, 0]
minStack.push(-3);    // Stack: [-2, 0, -3]
minStack.getMin();    // return -3
minStack.pop();       // Stack: [-2, 0]
minStack.top();       // return 0
minStack.getMin();    // return -2

Constraints ⚙️

  • -2^31 <= val <= 2^31 - 1

  • Methods pop, top, and getMin will always be called on non-empty stacks.

  • At most 3 * 10^4 calls will be made to push, pop, top, and getMin.


Solution 💡

To achieve O(1) time complexity for all operations, we can use two stacks:

  1. Primary stack to store all elements.

  2. Min stack to keep track of the minimum value at each level of the stack.

For every push, we add the value to the primary stack, and update the min stack with the current minimum value. For pop, we remove from both stacks.


Java Solution

class MinStack {
    private Stack<Integer> stack;
    private Stack<Integer> minStack;

    public MinStack() {
        stack = new Stack<>();
        minStack = new Stack<>();
    }

    public void push(int val) {
        stack.push(val);
        // Push the current minimum to the minStack
        if (minStack.isEmpty() || val <= minStack.peek()) {
            minStack.push(val);
        } else {
            minStack.push(minStack.peek());
        }
    }

    public void pop() {
        stack.pop();
        minStack.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }
}

Explanation of the Solution

  1. Two Stacks:

    • The main stack holds all the elements.

    • The min stack maintains the current minimum at every point.

  2. Push Operation:

    • Push the element onto the main stack.

    • Update the min stack with the smaller of the new element and the current minimum.

  3. Pop Operation:

    • Remove the top element from both stacks.

  4. Top Operation:

    • Return the top element of the main stack.

  5. GetMin Operation:

    • Retrieve the top element of the min stack, which represents the minimum.


Time Complexity ⏳

  • Push: O(1)

  • Pop: O(1)

  • Top: O(1)

  • GetMin: O(1)

Space Complexity 💾

  • O(n): We use two stacks, each storing up to n elements.

You can find the full solution .

LeetCode Problem Link
here