A string of brackets is balanced when every ( can be paired with a ) that comes after it, and every ) with a ( before it, without pairs crossing: (), (()) and ()(()) are balanced, while )( and (() are not.
Given a string s made only of ( and ), return the length of its longest substring that is balanced. A substring is a run of consecutive characters of s. If no substring is balanced (including when s is empty), return 0.
The run (()()) is balanced. The ) at the very start has nothing to close, and the ( at the very end is never closed, so neither can join it.
The third character is a ( that is never closed. It splits the string, so the two () pairs on either side of it cannot be joined into one run of four.
The ) at index 2 has no partner and splits the string. After it, (()) is balanced, and the ( in front of it is left open.
Constraints
0 <= s.length <= 3 * 10⁴s is ( or ).A ) that has nothing to close splits the string: no balanced run can cross it. A ( that is never closed splits it too, but you only learn which ones stay open once you reach the end.
Checking one substring is easy: walk it with a counter, +1 for ( and -1 for ). It is balanced when the counter never drops below 0 and ends at 0. The slow plan does that from every starting index, and a string of 3 · 10⁴ characters has about 4.5 · 10⁸ start and end pairs.
Time O(n)Space O(n)
The full walkthrough and code are part of Premium