Stacks and Queues
Balanced Parentheses
Walk a string of bracket characters. Push every opening bracket. On a closing bracket, pop and verify it matches; mismatch or empty-stack pop means unbalanced. At end of string, stack must be empty.
Algorithm
Canonical input "({[]})" (balanced) finishes with the stack empty and
the result true.
Basic Implementation
basic.cpp
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
int main() {
std::string text = "({[]})";
std::unordered_map<char, char> pairs = {{')', '('}, {']', '['}, {'}', '{'}};
std::vector<char> stack;
bool balanced = true;
for (size_t i = 0; i < text.length(); ++i) {
char ch = text[i];
if (ch == '(' || ch == '[' || ch == '{') {
stack.push_back(ch);
} else {
if (stack.empty() || stack.back() != pairs[ch]) {
balanced = false;
break;
}
stack.pop_back();
}
}
if (!stack.empty()) {
balanced = false;
}
std::cout << (balanced ? "true" : "false") << std::endl;
return 0;
}
Complexity
- Time: O(n)
- Space: O(n) worst case
Implementation notes
- C++: a plain
std::vector<char>doubles as a stack viapush_backandpop_back; avoidstd::stackto keep the iteration shape visible. - The
std::unordered_map<char, char>documents the closing -> opening map without leaking object identity into the replay. - The replay highlights the current character, shows the stack updating each frame, and surfaces the final balanced/unbalanced verdict.
stack push/pop
Use a plain `std::vector<char>` (`push_back` / `pop_back` / `back`) as the stack.
matching map
A small `std::unordered_map<char, char>` mapping each closing bracket to its expected opener keeps the lesson compact.