Longest Balanced Stretch in Text with Brackets
Updated
Problem statement
You are given a string s made of lowercase letters and the round brackets '(' and ')'. The brackets do not have to match.
A stretch is a non-empty run of consecutive characters of s. A stretch is balanced if, after you ignore its letters, its brackets form a valid sequence: every '(' has a later ')' that closes it, and every ')' closes an earlier '(' inside the same stretch. A stretch with no brackets at all is balanced.
Return the length of the longest balanced stretch, counting its letters as well as its brackets. If no stretch is balanced, return 0.
Function
longestBalancedStretch(s: String) → intExamples
Example 1
s = "(a)b((c)"return = 4The stretch "(a)b" has one matched pair and two letters, so it is balanced and has length 4. The '(' at index 4 is never closed, so no balanced stretch can contain it. To its right, "(c)" is balanced but has length only 3. The answer is 4.
Example 2
s = "a)b(c)d"return = 5The ')' at index 1 has no partner, so no balanced stretch can contain it. To its right, "b(c)d" is balanced: ignoring the letters it is just "()". Letters count toward the length, so the answer is 5.
Example 3
s = "))(("return = 0Every stretch with at least one character contains a bracket with no partner inside that stretch, so the answer is 0.
Constraints
1 <= s.length <= 2 * 10^4scontains only lowercase English letters,'('and')'.
More Rippling Onsite Interview questions
- Filter, Sort, and Deduplicate Scheduled TasksPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Stateful Log Transform and SearchPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Camel CardsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Corporate Card Expense RulesOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Limit an Organization Tree's HeightPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Delivery Cost TrackerPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Maximum Currency Conversion Along a Simple PathPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
- Top K Frequent WordsPHONE SCREEN · ONSITE INTERVIEW · Seen Aug 2026
- Future-Effective Employee SalaryONSITE INTERVIEW · Seen Aug 2026
- Filter and Sort Scheduled TasksONSITE INTERVIEW · Seen Jul 2026
Similar questions at other companies
- All Balanced Strings from Minimum Parenthesis InsertionsRubrik · ONSITE INTERVIEW
- Parse Boolean Rule ExpressionsStripe · PHONE SCREEN · ONSITE INTERVIEW
- Basic CalculatorAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Longest Valid ParenthesesMathWorks · ONSITE INTERVIEW
- Longest Valid ParenthesesMicrosoft · ONSITE INTERVIEW
- Longest Valid ParenthesesMaven Clinic · ONSITE INTERVIEW
- Evaluate an Arithmetic Expression with DivisionMotive · ONSITE INTERVIEW
- Single-Pass S-Expression ParserBaseten · ONSITE INTERVIEW
- Valid ParenthesesEPAM · ONSITE INTERVIEW
- Compress Editor Actions into Operational Transform OperationsReplit · OA · PHONE SCREEN · ONSITE INTERVIEW