from typing import List
from collections import deque
def is_valid(s: str) -> bool:
count = 0
for c in s:
if c == '(': count += 1
elif c == ')':
count -= 1
if count < 0:
return False
return count == 0
def remove_invalid_parentheses_bfs(s: str) -> List[str]:
res = []
visited = set([s]) # STEP 1
queue = deque([s]) # STEP 1
found = False # STEP 1
while queue: # STEP 2
size = len(queue)
for _ in range(size):
curr = queue.popleft() # STEP 2
if is_valid(curr): # STEP 8,10
res.append(curr) # STEP 8,10
found = True # STEP 8,10
if found:
continue # STEP 9
for i in range(len(curr)): # STEP 3-5,7
if curr[i] not in ('(', ')'):
continue
next_str = curr[:i] + curr[i+1:]
if next_str not in visited:
visited.add(next_str)
queue.append(next_str)
if found: # STEP 11
break
return res
if __name__ == "__main__":
test_str = "()())()"
print(remove_invalid_parentheses_bfs(test_str))
📊
Remove Invalid Parentheses - Watch the Algorithm Execute, Step by Step
Watching the algorithm step-by-step reveals how BFS ensures minimal removals and how pruning works by stopping deeper levels once valid strings are found.
Hint: Remember to convert k to zero-based before indexing [OK]
Common Mistakes:
Off-by-one error in k adjustment
Wrong index calculation in loop
Not popping used numbers
2. Examine the following buggy code snippet for Expression Add Operators. Which line contains the subtle bug that causes incorrect results on inputs with leading zeros?
def addOperators(num: str, target: int) -> List[str]:
res = []
path = []
def backtrack(index: int, evaluated: int, last_operand: int):
if index == len(num):
if evaluated == target:
res.append(''.join(path))
return
for i in range(index, len(num)):
# Bug: missing leading zero check
curr_str = num[index:i+1]
curr = int(curr_str)
length_before = len(path)
if index == 0:
path.append(curr_str)
backtrack(i+1, curr, curr)
path[length_before:] = []
else:
path.append('+'); path.append(curr_str)
backtrack(i+1, evaluated + curr, curr)
path[length_before:] = []
backtrack(0, 0, 0)
return res
medium
A. Line with 'if i != index and num[index] == '0':' missing here
B. Line with 'curr_str = num[index:i+1]' (substring extraction)
C. Line with 'path[length_before:] = []' (backtracking cleanup)
D. Line with 'path.append('+'); path.append(curr_str)' (operator insertion)
Solution
Step 1: Identify handling of leading zeros
The code lacks the check 'if i != index and num[index] == '0': break' which prevents invalid operands like "05".
Step 2: Confirm bug location
This missing check is critical and should be placed before parsing curr_str to avoid invalid expressions.
Final Answer:
Option A -> Option A
Quick Check:
Missing leading zero check causes invalid operands [OK]
Hint: Leading zero check missing causes invalid operands [OK]
Common Mistakes:
Confusing backtracking cleanup lines as bug
Thinking substring extraction is buggy
3. The following code attempts to solve N-Queens using bitmask backtracking. Which line contains a subtle bug that can cause invalid solutions or missed solutions?
medium
A. Line extracting rightmost 1-bit as position
B. Line updating diag1 and diag2 with incorrect bit shifts in recursive call
C. Line computing available_positions with bitmask and negation
D. Line resetting board[row][col] to '.' after recursion
Solution
Step 1: Identify bit shift directions for diagonals
diag1 (major diagonal) must be shifted left by 1, diag2 (minor diagonal) shifted right by 1 to reflect next row attacks.
Step 2: Check recursive call shifts
The code incorrectly shifts diag1 right and diag2 left, reversing the attack directions, causing invalid pruning.
Final Answer:
Option B -> Option B
Quick Check:
Correct diagonal shifts are diag1 << 1 and diag2 >> 1 [OK]
Hint: Diagonal attack masks must shift opposite directions each row [OK]
Common Mistakes:
Swapping diag1 and diag2 shifts
Not resetting board after recursion
Incorrect bitmask negation
4. What is the time complexity of the optimal factorial-based algorithm to find the k-th permutation of n numbers, and why?
medium
A. O(n^2) because each of the n iterations involves removing an element from a list of size up to n.
B. O(n!) because it generates all permutations internally.
C. O(n log n) due to sorting operations inside the algorithm.
D. O(n) because factorial computations and indexing are constant time per iteration.
Solution
Step 1: Analyze the main loop
The algorithm runs a loop n times to select each digit of the permutation.
Step 2: Consider list removal cost
Removing an element from the numbers list is O(n) in worst case, so total is O(n * n) = O(n^2).
Final Answer:
Option A -> Option A
Quick Check:
Each iteration's pop is linear, leading to quadratic time [OK]
Hint: List pop at arbitrary index costs O(n), not O(1) [OK]
Common Mistakes:
Assuming factorial computations dominate time
Thinking it's O(n) due to fixed loop count
Confusing factorial precomputation with sorting
5. The following code attempts to generate all permutations of a list using Heap's algorithm but contains a subtle bug:
def permute(nums):
res = [nums[:]]
c = [0] * len(nums)
i = 0
while i < len(nums):
if c[i] < i:
if i % 2 == 0:
nums[0], nums[i] = nums[i], nums[0]
else:
nums[c[i]], nums[i] = nums[i], nums[c[i]]
res.append(nums)
c[i] += 1
i = 0
else:
c[i] = 0
i += 1
return res
What is the bug in this code?
medium
A. The used array c is not reset properly, causing infinite loop
B. Appending nums directly without copying causes all entries in res to reference the same list
C. Swapping nums[0] and nums[i] when i is even is incorrect logic
D. The initial res list should be empty, not contain nums[:] at start
Solution
Step 1: Identify how results are stored
The code appends nums directly to res without copying.
Step 2: Understand consequences of appending references
Since nums is mutated in-place, all entries in res point to the same list, resulting in duplicates of the final permutation.
Final Answer:
Option B -> Option B
Quick Check:
Appending a copy nums[:] fixes the bug [OK]
Hint: Always append a copy of mutable lists to results [OK]
Common Mistakes:
Forgetting to copy before appending results in duplicate references
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.