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.php
<?php
function match_open($close) {
if ($close == ')') {
return '(';
} else if ($close == ']') {
return '[';
} else if ($close == '}') {
return '{';
}
return ' ';
}
$text = "({[]})";
$stack = [];
$balanced = true;
$i = 0;
while ($balanced && $i < strlen($text)) {
$ch = $text[$i];
if ($ch == '(' || $ch == '[' || $ch == '{') {
$stack[] = $ch;
} else {
if (count($stack) == 0 || $stack[count($stack) - 1] != match_open($ch)) {
$balanced = false;
} else {
array_pop($stack);
}
}
$i = $i + 1;
}
if (count($stack) != 0) {
$balanced = false;
}
if ($balanced) {
echo "True\n";
} else {
echo "False\n";
}
Complexity
- Time: O(n)
- Space: O(n) worst case
Implementation notes
- PHP: a plain
arraywith$stack[] = $ch;/array_pop($stack);/$stack[count($stack) - 1]is the smallest honest stack shape; reaching forSplStackwould hide the explicit push/pop pattern. A$balancedflag pluswhile ($balanced && $i < strlen($text))keeps the early-exit visible without leaning onbreak;. - The
match_openhelper documents the closing -> opening map without leaking runtime references into the replay. strlen($text)is the canonical character count for an ASCII bracket string; the lesson does not exercise multibyte sequences.- 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 `$stack = []` array as the open-bracket stack; push by `$stack[] = $ch;`, pop by `array_pop($stack);`.
matching map
A small `match_open($close)` helper returns the expected opener for each closing bracket — three explicit `if` arms keep the lesson compact.