FunctionRacerProblemsRace

First Unmatched Bracket

EasyStacks and queuesPython, JavaScript, TypeScript, Java, C++

s contains the brackets (), [] and {} and possibly other characters, which you ignore. Scan from left to right with a stack. Return the index of the first closing bracket that does not match the most recent open bracket (or has none to match). If every closing bracket matches but some opening brackets are never closed, return the index of the earliest of those unclosed opening brackets. If everything is matched, return -1.

Example 1

s "a(b]c"
returns 3

The ] at index 3 does not match the open (.

Example 2

s "(()"
returns 0

The first ( at index 0 is never closed.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Stacks and queues problems