← Questions

Longest valid bracket substring with nesting ranks

0
UberCoding

A coding interview question asked at Uber. It tests stack, strings and parentheses.

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 "{}[()]".

Clarifying questions

  • Does the rank rule apply only to pairs directly inside, or to every pair at any depth? (With these ranks the two readings give the same answer, and it helps to say why.)
  • When an outer pair breaks the rank rule, is its valid inside still a candidate? (Yes: "([])" contains "[]".)
  • Is the empty substring a valid answer of 0?
  • Can the input hold any other characters?

What a strong answer covers

  • Starts from the stack solution for the longest valid parentheses: keep the index of the last barrier, and measure each closed pair against the index below it on the stack.
  • Stores, for each open bracket on the stack, the highest rank closed directly inside it. When a pair closes, it passes its rank up to the bracket below it.
  • Treats a mismatched kind or a rank violation like an unmatched closer: nothing valid can span it, so the stack resets with a new barrier.
  • Shows that concatenation works: after a pair closes, its length joins the valid run to its left.
  • Stays O(n) time and memory. Tests "([])", "[{}]", "{{}}", "()[]{}", Example 2, and only closing brackets.

Follow-ups

  • Return the substring as well.
  • Ranks come from a table given as input, with more kinds of brackets.
  • Count all valid substrings.
  • Process the string as a stream and report the best length so far.

Where it's asked

What it tests

stack · strings · parentheses

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding