Finding the longest valid parentheses JavaScript

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

A set of parentheses qualifies to be a well-formed parentheses, if and only if, for each opening parentheses, it contains a closing parentheses.

For example:

'(())()' is a well-formed parentheses
'())' is not a well-formed parentheses
'()()()' is a well-formed parentheses

Algorithm Approach

The solution uses a stack-based approach to track invalid parentheses positions. We push indices of unmatched characters onto the stack, then calculate the longest valid substring between these invalid positions.

Example

const str = '(())()(((';

const longestValidParentheses = (str = '') => {
    var ts = str.split('');
    var stack = [], max = 0;
    
    ts.forEach((el, ind) => {
        if (el == '(') {
            stack.push(ind);
        } else {
            if (stack.length === 0 || ts[stack[stack.length - 1]] == ')') {
                stack.push(ind);
            } else {
                stack.pop();
            }
        }
    });
    
    stack.push(ts.length);
    stack.splice(0, 0, -1);
    
    for (let ind = 0; ind 

Output

6

How It Works

The algorithm works in three phases:

  1. Stack Processing: For each character, if it's '(' we push its index. If it's ')', we either pop a matching '(' or push the unmatched ')' index.
  2. Boundary Setup: Add -1 at the beginning and string length at the end to handle edge cases.
  3. Calculate Maximum: Find the largest gap between consecutive invalid positions in the stack.

Additional Example

// Test with different cases
console.log(longestValidParentheses('(()')); // 2
console.log(longestValidParentheses(')()())')); // 4
console.log(longestValidParentheses('()(())')); // 6
2
4
6

Conclusion

This stack-based solution efficiently finds the longest valid parentheses substring in O(n) time complexity. The key insight is tracking invalid positions and measuring gaps between them to find the longest valid sequence.

Updated on: 2026-03-15T23:19:00+05:30

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements