Balancing brackets = checking whether every opening bracket has a matching closing bracket in the correct order.
Types usually considered:
()[]{}
Core idea (stack method)
Use a stack:
- Read characters left → right.
- If opening bracket → push onto stack.
- If closing bracket →
- stack empty → invalid
- top doesn’t match → invalid
- else pop.
- End → stack must be empty.
Time: O(n)
Space: O(n)
Example
Input:
{[()]}
Process:
{ push
[ push
( push
) pop
] pop
} pop
Stack empty → balanced.
Python (clean version)
def is_balanced(s):
stack = []
pairs = {')': '(', ']': '[', '}': '{'}
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in ")]}":
if not stack or stack[-1] != pairs[ch]:
return False
stack.pop()
return len(stack) == 0
Edge cases people miss
"(]"→ order mismatch"((("→ leftover opens"))"→ early close""→ balanced"a+(b*c)"→ ignore non-brackets
Interview twist
If asked minimum removals to balance → count unmatched opens + closes while scanning once.
If asked longest valid parentheses → stack indexes or DP.
Further reading:
- Knuth — The Art of Computer Programming, Vol. 1 (stack parsing)
- Aho, Sethi, Ullman — Compilers: Principles, Techniques & Tools
Minimum C++ Question :
In C++, if bracket_pairs is a map, this call:
bracket_pairs.count('(');
checks whether '(' exists as a key in the map.
std::map::count(key) → returns:
1→ key exists0→ key absent
Example:
#include <iostream>
#include <map>
using namespace std;
int main() {
map<char,char> bracket_pairs;
bracket_pairs[')'] = '(';
bracket_pairs[']'] = '[';
bracket_pairs['}'] = '{';
cout << bracket_pairs.count('(') << endl;
}
Output
0
Reason:
'(' is a value, not a key.
Map content:
key → value
) → (
] → [
} → {
Check example:
bracket_pairs.count(')')
Output
1
Because ')' is a key.
Typical use in bracket algorithms:
if(bracket_pairs.count(ch))
Meaning:
Is this character a closing bracket?
If true → check matching opening bracket using stack.
Reference
https://en.cppreference.com/w/cpp/container/map/count
Fur
Comments
Post a Comment