Problem · String
Longest Valid Parentheses
Learn this problemProblem statement
Given a string s containing only ( and ), return the length of the longest contiguous substring that forms valid parentheses.
A parentheses string is valid when every opening parenthesis is matched with a later closing parenthesis and no prefix contains more closing parentheses than opening parentheses.
Function
longestValidParentheses(s: String) → intExamples
Example 1
s = "(()"return = 2The longest valid contiguous substring is (), with length 2.
Example 2
s = ")()())"return = 4The longest valid contiguous substring is ()(), with length 4.
Example 3
s = ""return = 0The empty string contains no non-empty valid substring.
Constraints
0 <= s.length <= 3 * 10^4scontains only(and).
More MathWorks problems
- Beautiful ArrangementONSITE INTERVIEW · Seen Jul 2026
- Find Minimum Cost to Remove Array ElementsONSITE INTERVIEW · Seen Jul 2026
- Group Shifted StringsONSITE INTERVIEW · Seen Jul 2026
- Balancing TeamsOA · Seen Nov 2025
- Largest Sub-GridOA · Seen Nov 2025
- Discount TagsOA · Seen Oct 2024
- Odd One OutOA · Seen Oct 2024
- Alloy ProductionOA · Seen Sep 2024