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.cs
using System;
using System.Collections.Generic;
class Program {
static char MatchOpen(char close) {
switch (close) {
case ')': return '(';
case ']': return '[';
case '}': return '{';
default: return (char)0;
}
}
static void Main() {
string text = "({[]})";
Stack<char> stack = new Stack<char>();
bool balanced = true;
for (int i = 0; i < text.Length; i++) {
char ch = text[i];
if (ch == '(' || ch == '[' || ch == '{') {
stack.Push(ch);
} else {
if (stack.Count == 0 || stack.Peek() != MatchOpen(ch)) {
balanced = false;
break;
}
stack.Pop();
}
}
if (stack.Count != 0) {
balanced = false;
}
Console.WriteLine(balanced ? "True" : "False");
}
}
Complexity
- Time: O(n)
- Space: O(n) worst case
Implementation notes
- C#:
Stack<char>withPush/Pop/Peekis the smallest honest stack shape; the standard library has a dedicated stack type that keeps the lesson on the explicit push/pop pattern instead of leaning on a genericList<T>. - The
MatchOpenhelper documents the closing -> opening map without leaking runtime references 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 `Stack<char>` for the open-bracket stack; push by `stack.Push(ch)`, pop by `stack.Pop()`.
matching map
A small `MatchOpen(close)` helper returns the expected opener for each closing bracket — three explicit `switch` arms keep the lesson compact.