Length of the Longest Valid Substring

Pattern: Balanced brackets

medium

Push indexes of ( onto a stack, with -1 at the bottom as the index just before the current run. A ) pops; if the stack is then empty, this ) breaks the run and its index becomes the new base. Otherwise the run ending here has length i minus the top.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given a string of ( and ), return the length of the longest substring that is balanced. "((()" gives 2 and ")()())" gives 4.

The catalogue has no practice link; LeetCode's Longest Valid Parentheses asks the same question.

Think first

  • What breaks a valid run?
  • If you know where the current run started, how long is it?
  • Why push indexes, not characters?

Hints

    Brute force, and why it fails

    Check every substring for balance: O(n³), or O(n²) with a running count from each start.

    The key insight

    Keep at the bottom of the stack the index just before the current run. After matching a ), whatever is on top is the start boundary, so the length is i - top.

    Dry run

    )0i
    (1 
    )2 
    (3 
    )4 
    )5 
    stack0

    s = ")()())". Start with [-1]. i = 0 is ): pop -1, the stack is empty, push 0 as the new base.

    Step 1 of 4

    The plan

    stack = [-1]; best = 0
    for i, c in s:
        if c == '(': push i
        else:
            pop
            if stack empty: push i
            else: best = max(best, i - top)
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each index is pushed and popped at most once.

    Edge cases

    • Empty string: 0.
    • Only openers: 0.
    • ()(): the runs join, giving 4.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int findMaxLen(String s) {
            Deque<Integer> st = new ArrayDeque<>();
            st.push(-1);                            // the index just before the current valid run
            int best = 0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '(') st.push(i);
                else {
                    st.pop();                       // match with the latest '(' (or drop the base)
                    if (st.isEmpty()) st.push(i);   // an unmatched ')': the next run starts after it
                    else best = Math.max(best, i - st.peek());   // the run since the index below
                }
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int findMaxLen(string s) {
            stack<int> st;
            st.push(-1);                            // the index just before the current valid run
            int best = 0;
            for (int i = 0; i < static_cast<int>(s.size()); i++) {
                if (s[i] == '(') st.push(i);
                else {
                    st.pop();                       // match with the latest '(' (or drop the base)
                    if (st.empty()) st.push(i);     // an unmatched ')': the next run starts after it
                    else best = max(best, i - st.top());   // the run since the index below
                }
            }
            return best;
        }
    };

    Python

    class Solution:
        def findMaxLen(self, s: str) -> int:
            st, best = [-1], 0                      # st[0]: the index just before the current valid run
            for i, c in enumerate(s):
                if c == "(":
                    st.append(i)
                else:
                    st.pop()                        # match with the latest '(' (or drop the base)
                    if not st:
                        st.append(i)                # an unmatched ')': the next run starts after it
                    else:
                        best = max(best, i - st[-1])   # the run since the index below
            return best

    Common mistakes

    • Starting with an empty stack instead of [-1].
    • Measuring i - popped index + 1, which misses joined runs like ()().

    Similar problems