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.
s is a null-terminated string containing bracket characters.
int balanced_brackets(const char *s) { /* TODO */ return 0; }
Stack underflow when encountering closing bracket with empty stack.
Empty string, string with only openers, string with only closers, mismatched types.
O(strlen).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.