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.js
const text = "({[]})";
const pairs = { ")": "(", "]": "[", "}": "{" };
const stack = [];
let balanced = true;
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (ch === "(" || ch === "[" || ch === "{") {
stack.push(ch);
} else {
if (stack.length === 0 || stack[stack.length - 1] !== pairs[ch]) {
balanced = false;
break;
}
stack.pop();
}
}
if (stack.length !== 0) {
balanced = false;
}
console.log(balanced);
Complexity
- Time: O(n)
- Space: O(n) worst case
Implementation notes
- JavaScript: a plain array doubles as a stack via
pushandpop; avoid any external stack library. - 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 array (`push` / `pop`) as the stack.
matching map
A small object literal mapping each closing bracket to its expected opener keeps the lesson compact.