Problem 594355 · hard · Phase 05 Advanced Algorithms & Graphs

Longest Balanced Bracket Stretch

dynamic programming · 1-D dp · brackets · substrings

A code editor highlights the longest contiguous part of a line that is perfectly balanced. The line s contains only the characters (, ), [ and ]. A stretch is balanced if every bracket is closed by a bracket of the same kind, in the right order, and nothing is left open (so ([])[] is balanced but ([)] is not). Return the length of the longest balanced stretch, or 0 if there is none.

Examples

Input:  s = "([)]()[]"
Output: 4
Explanation: "()[]" at the end; the first four characters interleave the two kinds.

Input:  s = "(([]))["
Output: 6

Constraints

  • 0 <= len(s) <= 10**5
  • Target complexity: O(n) time; checking every substring is at least quadratic.

Goals

  • Define the dp value as the longest balanced stretch ending exactly at each index
  • Glue a newly closed pair to the balanced stretch just before it
  • Handle two bracket kinds without mixing them up
Starting Python…