AlgoMaster Logo

Longest Valid Parentheses

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The simplest way to solve this problem is to generate all possible substrings and check each one to determine if it is a valid parentheses string. A valid parentheses string must have balanced opening and closing parentheses.

Methodology:

  • Iterate over all possible substrings of the given string.
  • For each substring, check if it is valid by ensuring that the count of '(' matches the count of ')'.
  • Track the length of the longest valid substring found.

Code:

2. Using a Stack

Intuition:

A stack can help keep track of indices of unmatched '(' characters. Whenever a valid pair is found, calculate the length of valid substrings till then using these indices from the stack.

Methodology:

  • Use the stack to store the indices of '(' characters.
  • When a ')' is encountered, pop from the stack; if the stack is empty, current valid substring length is zero, otherwise calculate the length from the new top of the stack.
  • Maintain a max length of such valid substrings.

Code:

3. Optimized Two-Pass Counter

Intuition:

Instead of using a stack, two traversals maintaining counters (left and right) to track opening '(' and closing ')' parentheses can be more space-efficient.

Methodology:

  1. Traverse the string from left to right:
    • Increment left counter for '(' and right counter for ')'.
    • If both counters are equal, update the max length found.
    • Reset counters if right becomes greater than left.
  1. Traverse again from right to left:
    • Use the same counters, but increment right for ')' and left for '(' to ensure all cases are checked.
    • Reset counters if left becomes greater than right.

Code: