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.ts
const text: string = "({[]})";
const pairs: Record<string, string> = { ")": "(", "]": "[", "}": "{" };
const stack: string[] = [];
let balanced: boolean = true;
for (let i: number = 0; i < text.length; i++) {
const ch: string = 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
- TypeScript: a plain
string[]array doubles as a stack viapushandpop; avoid any external stack library. - The
Record<string, string>annotation onpairsdocuments the closing -> opening map without leaking object identity. - 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 `string[]` array (`push` / `pop`) as the stack.
matching map
A small `Record<string, string>` mapping each closing bracket to its expected opener keeps the lesson compact.