833. Check brackets and report the first error position
Before parsing a model's structured output, you want a quick check that its brackets are balanced. Only (), [] and {} count; every other character is ignored.
Write first_bracket_error(s). Return -1 if every bracket is matched and correctly nested. Otherwise, if some closing bracket has no matching opener (or closes the wrong type), return the index of the first such closing bracket. If the scan ends with openers still unclosed, return the index of the earliest unclosed opener.
def first_bracket_error(s)Example 1
Input: first_bracket_error("f(a[1], {b})")
Output: -1
Example 2
Input: first_bracket_error("([)]")
Output: 2
Explanation: Because ")" tries to close "[".
Constraints
len(s)<= 100,000
Hint 1
Map each closer to its opener.
Hint 2
Push indices, not characters.
Hint 3
Leftover openers mean the string ended too early.
Common mistakes
- Only counting opens and closes, which accepts "([)]".
- Popping from an empty stack.
- Returning the last unclosed opener instead of the first.
Understand the idea
Bracket matching is the standard use of a stack: the most recently opened bracket must be closed first. For "{[()]" the stack goes {, {[, {[(, then ) pops (, ] pops [, and { remains, so the error is at index 0. Reporting a position instead of a yes or no answer is what makes the check useful for debugging model outputs.