You get a string s made of lowercase letters and the characters "(" and ")". Some parentheses may be unbalanced. Delete as few parentheses as you can so that the rest is balanced: every ")" closes an earlier "(", and every "(" is closed.
Return every different string you can reach with that smallest number of deletions, in any order. Letters are never deleted. If nothing but letters can stay, the answer holds the string of letters alone (possibly the empty string).
Example 1
Input: s = "(a))b)" Output: ["(ab)", "(a)b"] Why: two ")" have no partner; dropping two of the three gives these
2 more examples and the constraints
Example 2
Input: s = "))(("
Output: [""]
Why: no ")" has an earlier "(", so all four goExample 3
Input: s = "x(y"
Output: ["xy"]
Why: the lone "(" is never closedConstraints
- 1 ≤ length of s ≤ 25
- s has only lowercase English letters, "(" and ")"
- At most 20 characters of s are parentheses
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- BFS by removalsO(2ⁿ · n)
- Counted backtrackingO(2ⁿ · n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 25 characters | Verdict |
|---|---|---|---|
| BFS by removals | O(2ⁿ · n) | Passes; easy to argue minimal | |
| Counted backtracking | O(2ⁿ · n) | Best; only deletes what must go |
n = length of s. Both bounds are loose; the counted search touches far fewer strings.
Edge cases to test
- Already balanced. "()" is returned as is: zero deletions.
- Nothing can stay. "))((" gives [""], a list with one empty string, not an empty list.
- Only letters. "abc" has nothing to fix and comes back unchanged.
- Same answer two ways. In "(a))b)", deleting s[2] or s[3] both give "(a)b)". Return each string once.
- Both kinds extra. ")x(" loses one ")" and one "(" in the same answer: ["x"].
Common mistakes
- Returning duplicates, because deleting either of two equal neighbours gives the same string.
- Returning an empty list instead of [""] when every parenthesis must go.
- Stopping the BFS at the first valid string instead of collecting the whole level.
How to talk through it
- 1Clarify. Only parentheses can be deleted? Return all answers, unique, any order? Is [""] the answer when none can stay?
- 2Give the BFS. Levels by number of deletions; the first level with a valid string is minimal.
- 3Count the budget. One scan gives how many "(" and ")" must go. That bounds the search exactly.
- 4Code the backtracking. Recurse from the same index, skip runs of the same character, check at budget 0.
- 5Test out loud. Run "))((", "()" and "(a))b)" to cover empty, untouched and duplicate cases.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?