Make a Parentheses String Valid
Problem Description
Given a string s consisting of lowercase English letters and the characters '(' and )', the task is to remove the minimum number of parentheses to make the resulting string valid.
A string is considered valid if it adheres to the following rules:
- Every closing parenthesis
')'must have a corresponding opening parenthesis'('that appears before it. - The total count of opening parentheses must equal the total count of closing parentheses, ensuring overall balance.
The relative order of all remaining characters must be preserved. The function should return any valid string that can be obtained after performing 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:"()()"
Follow-ups
- Modify the function to return only the minimum number of parentheses that were removed.
- If multiple optimal valid strings exist (i.e., strings with the minimum number of removals), return the lexicographically smallest one.
- Discuss potential strategies to reduce the auxiliary space complexity of the solution.
AI interview prep
Core dilemma
Efficiently identifying and marking the minimum set of parentheses for removal while preserving relative order and handling both unmatched closing and opening parentheses.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Make a Parentheses String Valid
Problem Description
Given a string s consisting of lowercase English letters and the characters '(' and )', the task is to remove the minimum number of parentheses to make the resulting string valid.
A string is considered valid if it adheres to the following rules:
- Every closing parenthesis
')'must have a corresponding opening parenthesis'('that appears before it. - The total count of opening parentheses must equal the total count of closing parentheses, ensuring overall balance.
The relative order of all remaining characters must be preserved. The function should return any valid string that can be obtained after performing 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:"()()"
Follow-ups
- Modify the function to return only the minimum number of parentheses that were removed.
- If multiple optimal valid strings exist (i.e., strings with the minimum number of removals), return the lexicographically smallest one.
- Discuss potential strategies to reduce the auxiliary space complexity of the solution.