Leetcode #301: Remove Invalid Parentheses
In this guide, we solve Leetcode #301 Remove Invalid Parentheses in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return a list of unique strings that are valid with the minimum number of removals.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Breadth-First Search, String, Backtracking
Intuition
We must explore combinations of choices, but many branches can be pruned early.
Backtracking enumerates valid candidates while keeping the search space under control.
Approach
Use DFS to build candidates step by step, and backtrack when constraints are violated.
Pruning keeps the exploration practical for typical constraints.
Steps:
- Define the decision tree.
- DFS through choices and backtrack.
- Prune invalid paths early.
Example
Input: s = "()())()"
Output: ["(())()","()()()"]
Python Solution
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
def dfs(i, l, r, lcnt, rcnt, t):
if i == n:
if l == 0 and r == 0:
ans.add(t)
return
if n - i < l + r or lcnt < rcnt:
return
if s[i] == '(' and l:
dfs(i + 1, l - 1, r, lcnt, rcnt, t)
elif s[i] == ')' and r:
dfs(i + 1, l, r - 1, lcnt, rcnt, t)
dfs(i + 1, l, r, lcnt + (s[i] == '('), rcnt + (s[i] == ')'), t + s[i])
l = r = 0
for c in s:
if c == '(':
l += 1
elif c == ')':
if l:
l -= 1
else:
r += 1
ans = set()
n = len(s)
dfs(0, l, r, 0, 0, '')
return list(ans)
Complexity
The time complexity is Exponential (worst case). The space complexity is O(depth).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.