π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:
Every opening parenthesis '(' has a corresponding closing ')'.
The closing parenthesis appears after its matching opening parenthesis.
π Example Walkthrough:
Example 1:
Input:
s = "((()"Output:
2Explanation:
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)
Use a stack to track indices of parentheses.
Push opening parentheses ('(') indices onto the stack.
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:
Initialize a stack and push
-1as a base index.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()).
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++)
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