Skip to the code
+50 XP

#257 Longest Balanced Bracket Stretch

hard

A code editor highlights the longest stretch of a line that is made of balanced parentheses. A stretch is balanced when every ( in it is closed by a later ) in it, in the usual nested way, such as (())().

Write longestBalanced(text) that takes a string of only ( and ) and returns the length of its longest balanced substring (a run of neighboring characters). Return 0 if there is none.

Example 1

Input: text = "(()"
Output: 2

The longest balanced stretch is ().

Example 2

Input: text = ")()())"
Output: 4

()() in the middle has length 4.

Constraints

  • 0 <= text.length <= 10^5
  • text has only ( and ).
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).