What if you could instantly know if your code's brackets are perfectly matched without counting by hand?
Why Balanced Parentheses Problem Using Stack in DSA C++?
Imagine you are checking if a math expression typed by hand has matching parentheses. You try to count opening and closing brackets manually, but the expression is long and mixed with different types like (), {}, and [].
Manually counting or matching parentheses is slow and easy to mess up. You might miss a closing bracket or confuse the order, leading to wrong results and frustration.
Using a stack, you can quickly push each opening bracket and pop it when a matching closing bracket appears. This way, you keep track of the order and type, making the check fast and reliable.
bool isBalanced(string expr) {
int count = 0;
for (char ch : expr) {
if (ch == '(') count++;
else if (ch == ')') count--;
}
return count == 0;
}#include <stack> #include <string> using namespace std; bool isBalanced(string expr) { stack<char> stack; for (char ch : expr) { if (ch == '(' || ch == '[' || ch == '{') { stack.push(ch); } else if (ch == ')' || ch == ']' || ch == '}') { if (stack.empty()) return false; char top = stack.top(); stack.pop(); if ((ch == ')' && top != '(') || (ch == ']' && top != '[') || (ch == '}' && top != '{')) { return false; } } } return stack.empty(); }
This method enables fast and accurate validation of complex expressions with multiple types of parentheses.
Compilers use this technique to check if your code has correctly matched brackets before running it.
Manual counting is error-prone and slow.
Stack keeps track of opening brackets in order.
Matching closing brackets pop from the stack to verify correctness.
Practice
Balanced Parentheses Problem?Solution
Step 1: Understand the role of stack in matching parentheses
A stack stores opening parentheses as they appear, so we can check if each closing parenthesis matches the last opened one.Step 2: Explain why other options are incorrect
Sorting or counting parentheses does not help in matching pairs correctly. Reversing order is unrelated to matching.Final Answer:
To keep track of opening parentheses and match them with closing ones -> Option CQuick Check:
Stack matches parentheses pairs = C [OK]
- Thinking stack sorts parentheses
- Using stack to count parentheses only
- Ignoring order of parentheses
st?Solution
Step 1: Identify correct syntax for pushing a char onto stack
In C++, single quotes denote a char literal. Sost.push('(');correctly pushes the '(' character.Step 2: Explain why other options are incorrect
st.push("("); uses double quotes which is a string, not char. st.push((int)'('); uses wrong cast to int for char stack. st.push(')'); pushes a closing parenthesis, not opening.Final Answer:
st.push('('); -> Option DQuick Check:
Use single quotes for char push = A [OK]
- Using double quotes instead of single quotes
- Pushing wrong parenthesis character
- Using wrong cast type
std::stack<char> st;
std::string s = "({[]})";
for(char c : s) {
if(c == '(' || c == '{' || c == '[') st.push(c);
else {
if(st.empty()) { std::cout << "Not Balanced"; return 0; }
char top = st.top(); st.pop();
if((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
std::cout << "Not Balanced"; return 0;
}
}
}
if(st.empty()) std::cout << "Balanced";
else std::cout << "Not Balanced";Solution
Step 1: Trace the loop for each character in the string
Opening brackets are pushed onto the stack. For each closing bracket, the code checks if the top matches the corresponding opening bracket. The string "({[]})" is perfectly balanced.Step 2: Check stack emptiness after loop
After processing all characters, the stack is empty, so the output is "Balanced".Final Answer:
Balanced -> Option AQuick Check:
Matching pairs and empty stack = Balanced [OK]
- Not checking stack empty at end
- Mismatching pairs logic
- Ignoring early return on mismatch
std::stack<char> st;
std::string s = "(()";
for(char c : s) {
if(c == '(') st.push(c);
else if(c == ')') {
if(st.empty()) return false;
st.pop();
}
}
return true;Solution
Step 1: Analyze loop behavior on input "(()"
Two '(' are pushed, one ')' pops one '('. After loop, one '(' remains on stack.Step 2: Check final return statement
Code returns true without checking if stack is empty, so it incorrectly says balanced.Final Answer:
Does not check if stack is empty after loop -> Option BQuick Check:
Final stack empty check missing = A [OK]
- Missing final stack empty check
- Returning inside loop incorrectly
- Pushing wrong characters
s = "[{()}]({[]})", which of the following modifications to the balanced parentheses algorithm will correctly handle this input and also ignore any non-parenthesis characters like letters or digits?Solution
Step 1: Understand the need to ignore non-parenthesis characters
To handle strings with other characters, the algorithm must skip them and only process parentheses.Step 2: Explain why other options fail
Pushing all characters breaks logic. Counting only is insufficient. Checking half string misses pairs.Final Answer:
Add a condition to skip characters that are not '(', ')', '{', '}', '[' or ']' -> Option AQuick Check:
Process only parentheses characters = D [OK]
- Pushing non-parenthesis chars onto stack
- Counting parentheses without matching pairs
- Checking only part of the string
Ready to prove it?
Pass the test and this pattern moves unknown
