Longest Valid Parentheses
Updated
Problem statement
Given a string s made only of ( and ), return the length of the longest substring that is a valid parentheses string.
A substring is a run of characters that are next to each other in s. A valid parentheses string is one where every ( is closed by a later ) and every ) closes an earlier (, for example (), (()) or ()(()). If no such non-empty substring exists, return 0.
Function
longestValidParentheses(s: String) → intExamples
Example 1
s = ")()())"return = 4The substring ()() (characters 2 to 5) is balanced and has length 4. The first ) has nothing to close, and adding the last ) would close nothing either, so no longer balanced substring exists.
Example 2
s = "(()"return = 2Only () at the end is balanced. The first ( is never closed, so the answer is 2.
Example 3
s = ""return = 0The empty string has no characters, so the answer is 0.
Constraints
0 <= s.length <= 3 * 10^4- Every character of
sis(or).
More Microsoft Onsite Interview questions
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
- Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
- Smallest Batch Size Within a Step LimitONSITE INTERVIEW · Seen Nov 2026
- Count Subarrays with Equal Even and Odd CountsONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Rot All OrangesONSITE INTERVIEW · Seen Nov 2026
- Coin ChangeONSITE INTERVIEW · Seen Oct 2026
- Daily USD Totals with Effective-Dated Exchange RatesONSITE INTERVIEW · Seen Oct 2026
- Number Words to Digits in Any LanguageONSITE INTERVIEW · Seen Oct 2026
- Totals from a Tiered Rate TableONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Longest Valid ParenthesesMathWorks · ONSITE INTERVIEWMathWorks interview questions
- Longest Valid ParenthesesMaven Clinic · ONSITE INTERVIEWMaven Clinic interview questions
- Longest Valid ParenthesesApple · PHONE SCREENApple interview questions
- Longest Properly Closed Bracket RunAdobe · PHONE SCREENAdobe interview questions
- Minimum Insertion Steps to Make a String PalindromeInfosys · ONSITE INTERVIEWInfosys interview questions
- Wildcard MatchingTripjack · ONSITE INTERVIEWTripjack interview questions
- All Balanced Strings from Minimum Parenthesis InsertionsRubrik · ONSITE INTERVIEWRubrik interview questions
- Concatenated WordsAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Parse Boolean Rule ExpressionsStripe · PHONE SCREEN · ONSITE INTERVIEWStripe interview questions
- Interleaving StringsCARS24 · ONSITE INTERVIEW