Longest valid bracket substring with nesting ranks

0
Sign in

Given a string made only of the characters (, ), [, ], { and }, return the length of the longest contiguous substring that is valid.

A string is valid when all of these hold:

  1. Every bracket is closed by a bracket of the same kind, and pairs close in the right order (ordinary balanced brackets).
  2. The kinds have a rank: curly {} is highest, square [] is in the middle, and round () is lowest. A pair may directly contain pairs of the same or lower rank only. So {[()]}, {{}} and [()()] are valid, but ([]) and [{}] are not.
  3. Concatenating valid strings gives a valid string, in any order. For example, ()[]{} is valid.
def longest_valid(s: str) -> int: ...

Return 0 if no valid substring exists.

Constraints: 0 <= len(s) <= 10^5. Aim for O(n) time.

Example 1. s = "){[()]}[]((" returns 8, for the substring "{[()]}[]".

Example 2. s = "({}[()])" returns 6. The string is balanced, but ( may not contain { or [, so the outer pair is not valid. The longest valid substring is "{}[()]".

Reconstructed from the reported question; details may differ from what interviewers ask.

UberCodingHard

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.