Min Stack Problem Solution in C++ with Two-Stack Approach

🚀 Day 114 of My DSA Problem Solving Journey - The Grind Continues! 🎉 After tackling some quick string manipulation yesterday, today I shifted gears to Stack data structures! I took on LeetCode's "Min Stack" (Medium) in C++. The Problem: We need to design a custom stack that supports the usual operations (push, pop, top) BUT with a catch—we also need to retrieve the minimum element in constant O(1) time! My Approach: The tricky part is figuring out how to get the minimum value instantly without scanning the entire stack. To achieve this, I used a classic Two-Stack Approach. 🧠 The Logic: Two Stacks: I initialized a main stack (st) to store all the elements and an auxiliary stack (minSt) specifically to keep track of the minimum values at any given point. Push Operation: When pushing a new value, it always goes into the main stack. If the minSt is empty, OR if the new value is less than or equal to the current minimum (the top element of minSt), I push it onto minSt as well. Pop Operation: When popping, I check if the element being removed from the main stack is exactly the same as the current minimum at the top of the auxiliary stack. If it matches, I pop it from both stacks! Otherwise, just pop from the main stack. Retrieving Min: Because of how we maintained the auxiliary stack, calling getMin() is as simple as returning the top value of minSt. Zero searching required! Takeaway: This problem is a brilliant example of a Space-Time Tradeoff. By sacrificing a little bit of memory to maintain a second stack, we successfully optimized our time complexity to a strict O(1) for every single operation! ⚡ Keep pushing! 💻🔥 #Day114 #CPP #Stack #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #ContinuousLearning #REGexSoftwareServices

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories