Designing a Stack with Constant-Time Min Retrieval

🚀 DSA Challenge – Day 95 Problem: Design a Stack Supporting Constant-Time Minimum Retrieval 🧩📉 This is one of those elegant data structure design problems that sharpen your understanding of stack operations and auxiliary data structures! 🧠 Problem Summary: Implement a stack that, in addition to normal stack operations, can return the minimum element in O(1) time. The stack should support: ✅ push(val) → Insert an element. ✅ pop() → Remove the top element. ✅ top() → Return the top element. ✅ getMin() → Retrieve the minimum element — in constant time! ⚙️ My Approach: I used two stacks to achieve O(1) time complexity for all operations: 1️⃣ Main Stack (stack) → Stores all elements. 2️⃣ Min Stack (minStack) → Tracks the current minimum after each insertion. 🔹 When pushing a value, compare it with the current min and push it onto minStack if it’s smaller or equal. 🔹 When popping, if the popped element equals the current minimum, remove it from minStack as well. This ensures minStack always holds the minimum element at its top. 📈 Complexity: Time: O(1) for all operations Space: O(n) for the two stacks ✨ Key Takeaway: This problem beautifully demonstrates how an auxiliary data structure can optimize operations without affecting time complexity. Sometimes, solving problems efficiently is all about keeping track of the right information. ⚙️📚 🔖 #DSA #100DaysOfCode #LeetCode #ProblemSolving #MinStack #DataStructures #Stack #Algorithms #Python #CodingChallenge #EfficientCode #InterviewPrep #TechCommunity #LearningEveryday

  • text

To view or add a comment, sign in

Explore content categories