data-structures · beginner · ~20 min
Stack push/pop with a small alphabet; matching the right closer to the right opener.
Implement int balanced_brackets(const char *s) returning 1 if the string s has correctly nested and matched brackets, else 0.
Bracket pairs recognised: (), [], {}.
All non-bracket characters are ignored.
balanced_brackets("()") -> 1
balanced_brackets("(a + [b * c])")-> 1
balanced_brackets("{[()]}") -> 1
balanced_brackets("(]") -> 0 // mismatched closer
balanced_brackets("(") -> 0 // unclosed
balanced_brackets(")") -> 0 // closer with no opener
balanced_brackets("") -> 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.
Null-terminated string.
1/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.