KatInterview

Longest Well-Formed Bracket Run

Stacks & QueuesAuto-graded · 29 test cases
MediumAuto-gradedStacks & Queuesstackstringparentheses

Last updated

Find the length of the longest contiguous well-formed stretch in a string of only round brackets, testing stack-based index tracking and handling of unmatched characters.

You receive a string text made up solely of the characters ( and ).

Call a string well-formed if it follows these rules:

  • The empty string is well-formed.
  • If X is well-formed, then wrapping it as (X) gives a well-formed string.
  • If X and Y are both well-formed, then writing them side by side as XY gives a well-formed string.

Your task is to find the longest contiguous piece of text that is well-formed, and return its length. If no non-empty piece of text is well-formed, return 0.

Notes

  • A piece must be a run of consecutive characters. You may not skip characters.
  • Only the length is returned, so it does not matter which piece you pick when several pieces tie for the longest.
  • An empty input string yields 0.

Constraints

  • 0 <= len(text) <= 30000
  • Each character of text is either ( or ).

Examples

Example 1

Input: longest_wellformed_run(')(())()')

Output: 6

Example 2

Input: longest_wellformed_run('()(()')

Output: 2

Example 3

Input: longest_wellformed_run('))((')

Output: 0

Hints

Hint 1

Any well-formed piece ends at some `)`. Think about how to compute, for each position, how far to the left a well-formed piece ending there can reach.

Hint 2

Keep a stack of indices rather than characters. Seed it with `-1` so that a well-formed prefix can be measured the same way as any other piece.

Hint 3

On a `)`, pop first. If the stack is now empty, this `)` is unmatched: push its index as a new left boundary. Otherwise the current length is `i - stack[-1]`.