#301
Remove Invalid Parentheses
HardStringBacktrackingBreadth-First SearchBacktrackingBreadth-First Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a breadth-first search (BFS) approach to explore valid strings level by level, ensuring we only generate valid strings with the minimum number of removals. This method is efficient and avoids unnecessary checks.
⚙️
Algorithm
4 steps- 1Step 1: Count the number of misplaced '(' and ')' in the string.
- 2Step 2: Use a queue to perform BFS, starting with the original string.
- 3Step 3: For each string, generate all possible strings by removing one parenthesis and check for validity.
- 4Step 4: Stop when the first valid string is found and collect all unique valid strings.
solution.py26 lines
1# Full working Python code
2from collections import deque
3
4def is_valid(s):
5 count = 0
6 for char in s:
7 if char == '(': count += 1
8 if char == ')': count -= 1
9 if count < 0: return False
10 return count == 0
11
12def remove_invalid_parentheses(s):
13 result = set()
14 queue = deque([s])
15 found = False
16 while queue:
17 current = queue.popleft()
18 if is_valid(current):
19 result.add(current)
20 found = True
21 if found: continue
22 for i in range(len(current)):
23 if current[i] in '()':
24 next_str = current[:i] + current[i+1:]
25 queue.append(next_str)
26 return list(result)ℹ
Complexity note: The time complexity is O(n) because we only traverse the string a limited number of times, and we use a set to store unique valid strings, which takes linear time.
- 1Generating all possible strings is necessary to find valid combinations.
- 2Using BFS ensures we explore the shortest paths to valid strings first.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.