<AI/>
enru
Все статьи

Longest valid parentheses

LeetCode 32: Find the length of the longest valid parentheses substring, from a sliding window brute force to a linear stack solution.

Сложность
Сложная
Автор
Denis Kolpakov
Опубликовано
Темы
#stack
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

Write a function that finds the longest substring that is a valid parentheses sequence.

Input: a string s.

Output: the length of the longest substring that is a valid parentheses sequence.

Constraints

  • The string length is from 0 to 30000 characters
  • The string consists of the characters ( and )

Examples

Input: s = "(()"

Answer: 2

Explanation: The longest valid parentheses substring is ()

Sliding window approach

As usual, the first idea is brute force. Since we need the longest substring, we can start with substrings of maximum length and gradually move on to shorter ones until we find the first valid substring and return its length.

The sliding window technique helps here: we set the left bound to the first element and the right bound to the length of the current substring. We move the window from left to right, incrementing both bounds at the same time. If no valid substring of the given length is found, we decrease the length by one and check all possible substrings again.

Validity can be checked with a simple counter (since there's only one kind of bracket in this problem) or with a stack.

typescript
export function longestValidParenthesesWindowing(s: string): number {
  return recursiveLongestValidParenthesesWindowing(s, s.length);
}
 
function recursiveLongestValidParenthesesWindowing(s: string, substrLen: number): number {
  if (substrLen === 0) {
    return 0;
  }
 
  let left = 0;
  let right = substrLen;
 
  while (right <= s.length) {
    if (isValidParenthesesByCounter(s.substring(left, right))) {
      return right - left;
    }
    left++;
    right++;
  }
 
  return recursiveLongestValidParenthesesWindowing(s, substrLen - 1);
}
 
function isValidParenthesesByCounter(s: string): boolean {
  let counter = 0;
 
  for (const char of s) {
    if (char === '(') {
      counter++;
      continue;
    }
 
    if (counter === 0) {
      return false;
    }
 
    counter--;
  }
 
  return counter === 0;
}

Complexity Analysis

Time Complexity

Enumerating the windows takes O(n2), since each recursion level performs a linear pass over the string and there are n such levels. Checking each window adds another linear factor, so the brute force is really O(n3) in the worst case.

Space Complexity

The main factor is the recursion depth. Since each recursion level uses a constant amount of additional memory, the overall space complexity is O(n).

Keep in mind that this is a very inefficient algorithm. In JS, for example, it will cause a stack overflow on long strings.

Stack approach

The problem is actually quite easy: the longest valid parentheses substring is the largest distance between invalid parts of the string.

In other words, if we "cut out" the valid parentheses sequences from the string while keeping the indices of the remaining elements, the largest difference between two neighbouring indices is the number we're looking for. A stack helps us here.

We go through the string character by character:

  • If the current character is an opening bracket, push its index onto the stack.
  • If the current character is a closing bracket, pop the last index from the stack. If the stack becomes empty, push the current index onto it, since this position can serve as the start of the next substring. If the stack is not empty, compute the difference between the current index and the index on top of the stack (so we don't need an extra pass over the stack).

Initially, we push -1 onto the stack, which handles the case where the whole string is a valid parentheses sequence.

typescript
export function longestValidParenthesesStack(s: string): number {
  let stack: number[] = [-1];
  let res = 0;
 
  for (let i = 0; i < s.length; i++) {
    if (s[i] === '(') {
      stack.push(i);
      continue;
    }
 
    stack.pop();
    if (stack.length === 0) {
      stack.push(i);
      continue;
    }
 
    res = Math.max(res, i - stack[stack.length - 1]);
  }
 
  return res;
}

Complexity Analysis

Time Complexity

For this solution we go through the string just once, so the time complexity is O(n).

Space Complexity

This solution allocates additional memory for the stack. In the worst case all characters of the string end up on the stack, so the space complexity is O(n).