Delete the Fewest Parentheses to Balance a String of Only Open and Close Brackets
Company: Glean
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Given a string of only open and close parentheses, delete the fewest characters so the rest is balanced and return the resulting string, using standard left-to-right matching to define a unique answer. Tests bracket matching, linear-time scanning and careful handling of leftover unmatched characters.
Constraints
- 0 <= len(s) <= 10^5
- Every character of s is '(' or ')'.
Examples
Input: ('()())',)
Expected Output: '()()'
Explanation: Source example 1: the final ')' has no unpaired '(' before it and is deleted; the matching rule gives '()()' rather than the equally short '(())'.
Input: ('(()()',)
Expected Output: '()()'
Explanation: Source example 2: the '(' at index 0 is never paired and is deleted, giving '()()' and not '(())'.
Hints
- Apply the matching rule literally while scanning from left to right: when a ')' arrives, which '(' does it pair with, and what must you remember about the '(' characters seen so far?
- A ')' that arrives when every earlier '(' is already paired can never be paired later.
- Decide deletions by position: record which indices end up unpaired, then rebuild the string from the remaining characters in their original order.