FunctionRacerProblemsRace

Depth If Balanced

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

s is made of the brackets (), [] and {} only. It is balanced when every closing bracket closes the most recently opened bracket that is still open, the two are of the same kind, and nothing stays open at the end.

If s is balanced, return its nesting depth: the largest number of brackets that are open at the same moment. If s is not balanced, return -1. The empty string is balanced and has depth 0.

Example 1

s "([]{})"
returns 2

Everything matches. Inside the outer ( one more bracket opens, so two are open at once.

Example 2

s "([)]"
returns -1

) arrives while [ is the most recently opened bracket, so the string is not balanced.

Example 3

s ""
returns 0

Nothing is ever open, and an empty string counts as balanced.

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