Taro Logo

Longest Valid Parentheses

#2 Most AskedHard
Topics:
StringsDynamic ProgrammingStacks

Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

Example 2:

Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".

Example 3:

Input: s = ""
Output: 0

Constraints:

  • 0 <= s.length <= 3 * 104
  • s[i] is '(', or ')'.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the input string that we can expect, and are there any memory constraints?
  2. What should we return if the input string is empty, null, or contains no valid parentheses at all?
  3. Are we guaranteed that the input string will contain *only* '(' and ')' characters, or do we need to handle invalid characters?
  4. Does the definition of 'substring' imply that the characters must be contiguous in the original string?
  5. If there are multiple valid parentheses substrings of the exact same maximum length, does it matter which one we base our length calculation on (though the length will be the same)?

Brute Force Solution

Approach

Imagine you have a long mixed-up string of left and right parentheses, and you want to find the longest unbroken sequence where every opening parenthesis is properly closed. The brute force approach works by inspecting every single possible slice or portion of the string, one by one, to see how long it is and whether it is completely balanced.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first parenthesis and consider every possible ending point in the string to form a slice.
  2. For each slice you look at, examine the arrangement of left and right symbols from start to finish.
  3. Check if the slice has an equal number of opening and closing symbols, and ensure that a closing symbol never appears before its matching opening symbol.
  4. If the slice is valid and properly matched, measure its length and remember it if it is longer than any previous valid slice you have found.
  5. Move your starting point to the next parenthesis in line and repeat the entire process of checking every possible ending point.
  6. Continue this exhaustive search until you have tested every possible slice starting from every possible position in the original string.
  7. After checking every single possibility, report the length of the largest valid slice you discovered.

Code Implementation

def longest_valid_parentheses(parentheses_string):
    maximum_length = 0

    # Iterate through every possible starting position to exhaustively check all slices
    for start_index in range(len(parentheses_string)):
        for end_index in range(start_index + 2, len(parentheses_string) + 1, 2):
            current_slice = parentheses_string[start_index:end_index]
            balance_count = 0
            is_valid_slice = True

            for character in current_slice:
                if character == '(':
                    balance_count += 1
                else:
                    balance_count -= 1

                # Ensure closing parentheses never outnumber opening ones during the scan
                if balance_count < 0:
                    is_valid_slice = False
                    break

            # A valid slice must end with all opened parentheses properly closed
            if is_valid_slice and balance_count == 0:
                if len(current_slice) > maximum_length:
                    maximum_length = len(current_slice)

    return maximum_length

Big(O) Analysis

Time Complexity
O(n³) – Letting n be the length of the input string, the outer loop sets a starting point while the second loop determines every possible ending point, yielding about n squared slices to check. For each of these slices, we must examine the arrangement of symbols from start to finish, which takes linear time proportional to the length of the slice. Multiplying the n squared possible slices by the linear validation cost results in approximately cubed operations. This exhaustive search approximates a cubic formula that simplifies to a Big O time complexity of O(n³).
Space Complexity
O(1) – The brute force approach described relies entirely on iterating through the string with nested loops and a few primitive tracking variables to measure slice lengths. Because no auxiliary data structures, temporary lists, or recursive calls are utilized, the extra memory consumption remains constant. As the input string size N grows, the algorithm uses a fixed amount of auxiliary space for its counters and flags. Therefore, the total space complexity simplifies to Big O of 1.

Optimal Solution

Approach

Instead of testing every possible grouping of parentheses, the optimal approach scans the sequence methodically to track how many valid matches we can form on the fly. By keeping a running tally and resetting when things don't match up, we can find the longest unbroken streak efficiently in a single pass.

Here's how the algorithm would work step-by-step:

  1. Begin scanning the sequence of parentheses from the very beginning to the very end, keeping a mental tally of your current depth.
  2. Whenever you encounter an opening parenthesis, record its position so you can remember where a potential valid section might have started.
  3. Whenever you encounter a closing parenthesis, pair it with the most recent opening parenthesis you found.
  4. If you successfully pair them up, calculate the length of this current valid section by looking at how far back the opening partner was, and compare it to your record for the longest valid section found so far.
  5. If you ever find a closing parenthesis that does not have an opening partner to match with, it means the sequence is broken, so reset your starting point for future sections.
  6. To catch valid sections that might be hidden when reading strictly forward, repeat a similar scanning process moving backward from the end to the beginning.
  7. Combine the insights from both directions to ensure no valid stretching combination is missed, ultimately revealing the longest valid parentheses streak.

Code Implementation

def longest_valid_parentheses(parentheses_sequence):
    max_valid_length = 0
    open_count = 0
    close_count = 0

    for current_character in parentheses_sequence:
        if current_character == '(':
            open_count += 1
        else:
            close_count += 1

        if open_count == close_count:
            max_valid_length = max(max_valid_length, 2 * close_count)

        # Reset counts when unmatched closing parenthesis breaks the valid sequence.
        elif close_count > open_count:
            open_count = 0
            close_count = 0

    open_count = 0
    close_count = 0

    for current_character in reversed(parentheses_sequence):
        if current_character == ')':
            close_count += 1
        else:
            open_count += 1

        if open_count == close_count:
            max_valid_length = max(max_valid_length, 2 * open_count)

        # Reset counts when unmatched opening parenthesis breaks the backward sequence.
        elif open_count > close_count:
            open_count = 0
            close_count = 0

    # Combine insights from both scans to guarantee the absolute longest streak.
    return max_valid_length

Big(O) Analysis

Time Complexity
O(n) – Let n be the length of the string of parentheses. The algorithm performs two independent linear scans: one moving forward from the beginning to the end, and a second one moving backward from the end to the beginning. Each pass visits every character in the string exactly once to update the running tallies and calculate lengths. Combining the two passes results in roughly 2n total operations, which simplifies to the linear time complexity of O(n).
Space Complexity
O(1) – The algorithm relies solely on a few primitive integer variables to track the current depth, indices, and the running maximum length during the scans. Because no dynamic data structures, such as a stack or auxiliary arrays, are created during the forward and backward passes, the extra memory usage remains constant regardless of the input string length N.

Edge Cases

Empty string or null input
How to Handle:
Return zero immediately as no valid parentheses substring can exist.
String with a single character like '(' or ')'
How to Handle:
Return zero because a single parenthesis cannot form a valid pair.
String with all opening brackets like '((((('
How to Handle:
The stack or dynamic programming approach will correctly calculate a maximum length of zero.
String with all closing brackets like ')))))'
How to Handle:
Base pointers or stack resets ensure that unmatched closing brackets do not contribute to the length.
Valid parentheses starting with a closing bracket like ')(())'
How to Handle:
The algorithm resets its tracking when encountering an unmatched closing bracket, correctly evaluating the trailing valid substring.
Interleaved or nested valid substrings like '()(())'
How to Handle:
Using a stack of indices or a two-pass scan ensures that adjacent or nested valid parts merge correctly for the maximum length.
Maximum length constraints up to tens of thousands of characters
How to Handle:
An optimal O(n) time and O(n) space linear scan ensures the solution scales efficiently without hitting time limits or stack overflows.
Extremely long strings causing integer overflow
How to Handle:
Using standard integer types is safe since string lengths easily fit within typical 32-bit signed integer limits.
0/4 completed