← All Exercises

Balanced Brackets with a Stack

basicgo~20min

Background

A stack enforces last-in-first-out nesting; every closing bracket must match the most recent unmatched opening, which makes balance checking linear.

Problem

Given text containing (), [], and {}, return (valid bool, index int). Non-bracket characters are ignored. On a mismatched closing bracket, index is its rune position; on unclosed opening brackets, index is the most recent unmatched opening; on success index is -1.

Input

A UTF-8 string that may contain brackets and arbitrary other characters.

Output

A validity flag and the first error position, or -1 when the string is balanced.

Sample tests

Sample 1

Input: text = "{[()]}"
Expected: valid=true, index=-1

Sample 2

Input: text = "(]"
Expected: valid=false, index=1

Sample 3

Input: text = "(("
Expected: valid=false, index=1

Your solution

Learning objective

Use a stack to validate nested delimiters and report precise error positions in rune units.