data-structures · beginner · ~20 min
Stack push/pop with a small alphabet; matching the right closer to the right opener.
Check that all brackets in a string are correctly matched and nested.
Implement int balanced_brackets(const char *s) that returns 1 if the brackets in s are correctly matched and nested, else 0. Recognised pairs are (), [], and {}; all other characters are ignored.
s: a NUL-terminated string that may contain brackets and any other characters.
int: 1 if balanced, 0 otherwise.
"()" -> 1
"(a + [b * c])" -> 1
"{[()]}" -> 1
"(]" -> 0 (mismatched closer)
"(" -> 0 (unclosed)
")" -> 0 (closer with no opener)
"" -> 1 (empty is balanced)
A stack-based bracket checker is the simplest non-trivial use of a stack and a great warm-up for full expression parsers. The same logic powers IDE bracket-matching, JSON validators, and shell quoting checkers.
s: a NUL-terminated string; non-bracket characters are ignored.
int: 1 if brackets are balanced, else 0.
Use a stack (array). Maximum nesting depth assumed <= 512.
int balanced_brackets(const char *s) { /* TODO */ return 0; }
Just counting openers vs closers — fails on (]). Forgetting to check the stack is non-empty before peeking on a closer.
Empty; only openers; only closers; deeply nested; mixed bracket types.
O(strlen).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.