You are given a string s made only of the characters "(" and ")". Find the longest stretch of consecutive characters in which the brackets are balanced: every "(" is closed by a later ")", and no ")" closes something that was never opened.
Return the length of that stretch, or 0 if there is none.
Example 1
Input: s = "())(())" Output: 4 Why: "(())" at indices 3 to 6
2 more examples and the constraints
Example 2
Input: s = "()(()"
Output: 2
Why: the "(" at index 2 is never closedExample 3
Input: s = ")("
Output: 0
Why: neither bracket has a partnerConstraints
- 0 ≤ length of s ≤ 30,000
- Every character is "(" or ")"
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every start, running balanceO(n²)
- DP on the run ending at iO(n)
- Stack of indicesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 30,000 characters | Verdict |
|---|---|---|---|
| Every start, running balance | O(n²) | Correct, too slow | |
| DP on the run ending at i | O(n) | Passes; fiddly indices | |
| Stack of indices | O(n) | Best; one pass, easy to explain |
n = length of s.
Edge cases to test
- Empty string. Return 0; the loop never runs.
- Nothing matches. ")(" or "(((" gives 0.
- Side by side and nested. "()(())" is one run of 6: the runs join.
- An unclosed "(" in the middle. "(()(()" gives 2: the "(" at index 3 splits the string, and its index stays in the stack as a wall.
Common mistakes
- Counting all matched pairs in the string instead of the longest stretch without a break.
- Forgetting the −1 at the bottom, so a run that starts at index 0 is measured one short or crashes on an empty stack.
- In the DP, adding dp[j − 1] without checking j ≥ 1.
How to talk through it
- 1Clarify. Only round brackets? A substring, so the characters must be next to each other? What for an empty string?
- 2Give the brute force. Every start with a running balance; stop when it goes negative. O(n²).
- 3Find what breaks a run. An unmatched bracket is a wall. The answer is the widest gap between walls.
- 4Code the stack. Keep indices, seed with −1, and measure i − top after each pop. Say what the bottom item means.
- 5Test out loud. Run Example 1, "()(())" and the empty string.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?