πŸš€Day 2. Longest valid Parentheses 🧠

The problem can be found at the following link: Question Link

πŸ’‘ Problem Description:

Given a string s consisting of only '(' and ')', find the length of the longest valid parentheses substring.

A parenthesis string is valid if:

  1. Every opening parenthesis '(' has a corresponding closing ')'.

  2. The closing parenthesis appears after its matching opening parenthesis.

πŸ” Example Walkthrough:

Example 1:

Input:

s = "((()"

Output:

2

Explanation:

The longest valid parentheses substring is "()".

Example 2:

Input:

Output:

Explanation:

The longest valid parentheses substring is "()()".

Example 3:

Input:

Output:

Explanation:

The longest valid parentheses substring is "()".

Constraints:

  • $1 \leq s.length \leq 10^6$

  • s consists of '(' and ')' only.

🎯 My Approach:

Stack-Based Approach (O(N) Time, O(N) Space)

  1. Use a stack to track indices of parentheses.

  2. Push opening parentheses ('(') indices onto the stack.

  3. For closing parentheses (')'):

    • If the stack is not empty, pop the top element.

    • If the stack is empty, push the current index as a new base.

    • Maintain the maximum valid length by subtracting indices.

Algorithm Steps:

  1. Initialize a stack and push -1 as a base index.

  2. Traverse s character by character:

    • If '(', push its index onto the stack.

    • If ')', pop from the stack.

      • If the stack becomes empty, push the current index.

      • Otherwise, update max_length = max(max_length, i - st.top()).

  3. Return max_length.

πŸ•’ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(N), as we traverse the string once.

  • Expected Auxiliary Space Complexity: O(N), for storing indices in the stack.

πŸ“ Solution Code

Code (C++)

⚑ Alternative Approaches

2️⃣ Two-Pass Counter Approach (O(N) Time, O(1) Space)

  1. Use left-right counters to track valid parentheses.

  2. Forward pass ensures extra right brackets are ignored.

  3. Backward pass ensures extra left brackets are ignored.

πŸ”Ή Pros: No extra space needed. πŸ”Ή Cons: Requires two passes.

πŸ“Š Comparison of Approaches

Approach

⏱️ Time Complexity

πŸ—‚οΈ Space Complexity

βœ… Pros

⚠️ Cons

Stack (Using Indices)

🟒 O(N)

🟑 O(N)

Simple and effective

Extra stack memory used

Two-Pass Counter Approach

🟒 O(N)

🟒 O(1)

No extra space required

Requires two passes over input

πŸ’‘ Best Choice?

  • βœ… For best efficiency: Two-Pass Counter (O(N)) (No extra space).

  • βœ… For simpler implementation: Stack Approach (O(N)) (Easier to understand).

Code (Java)

Code (Python)

🎯 Contribution and Support:

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Last updated