Remove Invalid Parentheses
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Backtracking.
Remove Invalid Parentheses
Minimal Removal
To make a string valid with minimal removals, we first calculate the number of misplaced open
( and closed ) parentheses.BFS vs. Backtracking
- BFS: Guarantees finding the minimal removal level first. We remove one paren at a time and check validity.
- Backtracking: More memory efficient. We use the pre-calculated
remOpenandremClosedto limit our search space and prune invalid branches early.
Remove the minimum number of invalid parentheses to make the input string valid. Includes visual removal tree.
Examples
Input: s = "()())()"
Output: ["(())()","()()()"]
Approach 1
Level I: Backtracking with Pruning
Intuition
Count how many '(' and ')' need to be removed, then use DFS to try all removal combinations.
Calculate
remL and remR. In DFS, for each character: 1. If it's '(' and remL > 0, try removing it. 2. If it's ')' and remR > 0, try removing it. 3. Always try keeping it if valid.⏱ O(2^N)💾 O(N)
Detailed Dry Run
s="())", remL=0, remR=1
1. Index 0 '(': Keep it. (L=1, R=0)
2. Index 1 ')':
- Remove: DFS(idx 2, L=1, R=0) -> "()" Valid!
- Keep: (L=1, R=1)
3. Index 2 ')':
- Remove: DFS(idx 3, L=1, R=1) -> "()" Valid!Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.