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.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
static char match_open(char close) {
if (close == ')') return '(';
if (close == ']') return '[';
if (close == '}') return '{';
return 0;
}
int main(void) {
const char *text = "({[]})";
char stack[64];
int top = 0;
bool balanced = true;
for (size_t i = 0; i < strlen(text); ++i) {
char ch = text[i];
if (ch == '(' || ch == '[' || ch == '{') {
stack[top++] = ch;
} else {
if (top == 0 || stack[top - 1] != match_open(ch)) {
balanced = false;
break;
}
top--;
}
}
if (top != 0) {
balanced = false;
}
printf("%s\n", balanced ? "true" : "false");
return 0;
}
Complexity
- Time: O(n)
- Space: O(n) worst case
Implementation notes
- C: a fixed-size
char stack[64]plusint topmakes the iteration shape visible; there is nostd::stack-style wrapper hiding the push/pop indices. - The
match_openhelper 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 `char stack[64]` with an integer `top` index as the stack; push by `stack[top++] = ch`, pop by `--top`.
matching map
A small `match_open(close)` helper returns the expected opener for each closing bracket — three explicit cases keep the lesson compact.