data-structures · intermediate · ~15 min

Balanced brackets

Use a stack to match nested delimiters.

Challenge

Check whether the brackets in a string are correctly matched and nested.

Task

Implement int paren_balanced(const char *s) that returns 1 if every (, [, and { is matched with the correct closer in the correct nesting order, else 0. Characters that are not brackets are ignored.

Input

s: a NUL-terminated string that may contain (), [], {}, and any other characters.

Output

int: 1 if balanced, 0 otherwise.

Example

"a(b[c]{d})"   ->   1
"(]"           ->   0   (wrong closer)
"(("           ->   0   (unclosed)
""             ->   1   (empty is balanced)

Edge cases

  • Empty string is balanced (returns 1).
  • A closer with no matching opener returns 0.
  • Openers left unclosed at the end return 0.

Input format

s: a NUL-terminated string; non-bracket characters are ignored.

Output format

int: 1 if all brackets are matched and nested, else 0.

Constraints

Use a stack to track open brackets.

Starter code

int paren_balanced(const char *s) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.