Make a Parentheses String Valid
EightfoldaiSoftware Engineer · Technical ScreenLast updated
This question evaluates proficiency in string manipulation and delimiter matching, specifically balancing parentheses while preserving character order and handling edge cases.
Given a string s containing lowercase English letters and the characters '(' and ')', remove the minimum number of parentheses so that the resulting string is valid.
A string is considered valid if:
- every
')'has a matching'('before it, and - the total number of
'('and')'is balanced.
You must preserve the relative order of all remaining characters. Return any valid string that can be obtained after the minimum number of removals.
Examples:
- Input:
"lee(t(c)o)de)"-> Output:"lee(t(c)o)de" - Input:
"a)b(c)d"-> Output:"ab(c)d" - Input:
"))("-> Output:"" - Input:
"())()("-> Output:"()()"or another valid minimum-removal result
Possible follow-ups:
- Return only the minimum number of removals.
- If multiple optimal answers exist, return the lexicographically smallest valid result.
- Discuss whether the extra space can be reduced.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.