Stack Problems
Easy Problems:
Problem 1: Valid Parenthesis (Leetcode 20)
Alright, buckle up! We’re diving into the world of brackets, where ( wants to end up with ), and { is desperately looking for its soulmate }. And if they don’t find each other properly? Boom 💥—invalid!
Let’s break down this code in the most clear, and a bit funny way possible.
👨🏫 What does the code do?
It checks if a string made of brackets is balanced and valid. For example:
()[]{}{}✅ Valid([)]❌ Invalid((()❌ Invalid
🧠 Pseudocode (a.k.a. the story in plain English)
- Take an empty bag (stack) to keep track of opening brackets.
- For every character in the string:
- If it’s an opening bracket like
(or{or[, just throw it into the bag. - If it’s a closing bracket like
)or}or]: - Check if the bag is not empty (you can’t close something that wasn’t opened).
- Peek into the bag (check the last opened bracket).
- If it matches, remove it (Yay! They matched!).
- If it doesn’t match, return
false(Mismatch!).
- After checking everything, if the bag is empty — return
true(all brackets were matched properly). - If something is left in the bag — return
false(someone didn’t get a pair).
🪜 Step-by-Step Dry Run Example: "()[{}]"
(→ push)→ matches top(→ pop[→ push{→ push}→ matches top{→ pop]→ matches top[→ pop- Stack empty → ✅ Valid!
💡 Tricks & Tips:
- Stacks are perfect for problems with “Last In, First Out” (LIFO) logic. That’s why we use it here!
- Whenever you open something, just imagine you’re putting it on top of a stack.
- When closing something, you have to close the last thing you opened first — like nested Tupperware boxes 🥡.
- If at the end, your stack is empty, congratulations! Everything was properly closed.
- A common mistake: mismatching brackets (e.g., trying to close
[with)).
🧮 Time and Space Complexity
Time Complexity (TC): O(n)
We traverse the string once.
Space Complexity (SC): O(n)
In the worst case (like "(((([[[{{{"), all characters go into the stack.
🧰 Technique Used
🔁 Stack-based Validation
Get Eshwar Nagaraj’s stories in your inbox
Join Medium for free to get updates from this writer.
Why Stack?
- We need to know the last opened bracket every time we see a closing one.
- Stack gives you instant access to the top element (which is exactly what we need).
🔄 Other Ways To Solve It (Just technique names):
- Using a Hash Map + Stack (to make it cleaner with mappings)
- Recursive Approach (rarely used here, but possible)
- Two-pointer approach (not suitable here, but some try clever hacks)
- Regex (pattern matching) (not recommended — very hacky for this problem)
- Counter-based (Not for all bracket types) — works for single bracket type only
🤹 Bonus Fun Thought:
If you ever forget your wallet (like forgetting to close a {), your whole day is ruined. Same goes here — forget to close a bracket, and your code throws a tantrum. 😅
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i = 0; i < s.length(); i++){
char ch = s[i];
if((ch == '(') || (ch == '{') || (ch == '[')){
st.push(ch);
}else{
if(!st.empty()){
char tp = st.top();
if((ch == ')' && tp == '(') || (ch == '}' && tp == '{') || (ch == ']' && tp == '[')){
st.pop();
}else{
return false;
}
}else{
return false;
}
}
}
if(st.empty()){
return true;
}else{
return false;
}
}
};Hard Problems
Problem 1: Long Valid Parenthesis (Leetcode 32)
Alright! Let’s decode the mystery of matching parentheses again — but this time, we’re not just checking if the string is valid…
We’re hunting for the longest valid substring of parentheses.
Like, "(()"? Nah, just 2 are valid.
But "()(()))()"? That sweet (()))() has a valid streak of 6!
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
st.push(-1);
int max_len = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(') {
st.push(i);
} else {
st.pop();
if (st.empty()) {
st.push(i);
} else {
max_len = max(max_len, i - st.top());
}
}
}
return max_len;
}
};🔍 What does this code do?
It finds the length of the longest valid (well-formed) parentheses substring using stack magic 🧙♂️.
🧠 Pseudocode (Plain English Version)
- Start with a stack to track indices, not characters.
- Push
-1as a base (like a reference point). - For each character in the string:
- If it’s
'(', push its index into the stack. - If it’s
')': - Pop the top element (we’re trying to find a match for this
')') - If the stack becomes empty after popping, push the current index (new base).
- If not empty, calculate the valid length:
i - st.top(), and update the max length.
4. After loop ends, return max_len.
🎯 Step-by-Step Example: "(()())"
Initial stack: [-1]
i=0, '(': push → [-1, 0]
i=1, '(': push → [-1, 0, 1]
i=2, ')': pop → [-1, 0], max_len = 2 (2 - 0)
i=3, '(': push → [-1, 0, 3]
i=4, ')': pop → [-1, 0], max_len = 4 (4 - 0)
i=5, ')': pop → [-1], max_len = 6 (5 - (-1))✅ Final answer: 6
🧮 Time & Space Complexity
- Time Complexity:
O(n)— We go through the string only once. - Space Complexity:
O(n)— In worst case, we push all indices to stack (for many'('s).
🧰 Technique Used: Stack + Index Tracking
🔍 Why not just store characters?
Because we need to calculate lengths, and for that, we need to know positions.
If you just store '(', how do you calculate how far apart matching pairs are?
Hence, store indices.
💡 Tips & Tricks
- Always push
-1first! It acts as a fake open bracket at the start. Without it, you’d get wrong lengths. - When you hit a
')', alwayspopfirst. You're trying to close something. - If the stack is empty after popping, push the index of the
')'— it acts as a new base for future calculations. max_len = max(max_len, i - st.top())is the key calculation: difference between current index and last unmatched open.
😎 Human Analogy
Think of ( as opening a room door, and ) as closing it.
You walk through a hallway with many rooms.
Every time you properly open and close, you mark how long that clean stretch was.
If you close a door without opening it first (unmatched )), you stumble and say, “Let me start counting from here again.”
🛠️ Other Techniques to Solve This
- Two-pass scan with counters
- Forward and backward traversal using
leftandrightcounters - No stack used, more space-efficient.
2. Dynamic Programming (DP)
- Store at each index the length of the longest valid parentheses ending there.
3. Greedy + Two Pointers
- Similar to counter method but more optimized for space and faster checks.
🤯 Bonus Trick: Why Push -1?
Without it, when you pop the first unmatched (, your stack becomes empty — and then you get wrong calculations like i - ???.
By pushing -1, you're giving it a safe ground to fall back to, like a safety net. 🕸️








