FunctionRacerProblemsRace

Longest Balanced Piece

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

s is made of the brackets (), [] and {}. A piece of s (a run of consecutive characters) is balanced when each closing bracket in it matches the most recent bracket that is still open in the piece, which must be of the same kind, and nothing stays open at the end of the piece.

Return the length of the longest balanced piece, or 0 if there is none.

Example 1

s "([)]{}[]"
returns 4

([)] is not balanced because ) arrives while [ is the most recent open bracket, but {}[] is.

Example 2

s "(()[]{"
returns 4

The first ( is never closed, so the best piece is ()[].

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