Practice
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):
res = []
visited = set([s])
queue = deque([s])
found = False
while queue:
size = len(queue)
for _ in range(size):
curr = queue.popleft()
if is_valid(curr):
res.append(curr)
found = True
if found:
continue
for i in range(len(curr)):
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)
return res
print(remove_invalid_parentheses_bfs("()())()"))
What is the output of this code?Solution
Step 1: Trace BFS levels for input "()())()"
Initial string is invalid. BFS removes one parenthesis at each position generating candidates. The first valid strings found are "()()()" and "(())()".Step 2: Confirm both valid strings are collected
Since BFS stops adding new states after finding valid strings at current level, both minimal removal results are returned.Final Answer:
Option B -> Option BQuick Check:
Both minimal valid strings are returned [OK]
- Returning only one valid string
- Returning original invalid string
- Missing one minimal valid string
def get_candidates(r, c):
b = (r//3)*3 + c//3
return [ch for ch in '123456789' if ch not in rows[r] and ch not in cols[c] and ch not in boxes[b]]
empties.sort(key=lambda x: len(get_candidates(x[0], x[1])))
first_empty = empties[0]
candidates_len = len(get_candidates(first_empty[0], first_empty[1]))
What is the value of candidates_len?Solution
Step 1: Identify first empty cell after sorting
Check empties and compute candidates for each; the cell with fewest candidates is chosen first.Step 2: Calculate candidates for first empty cell (0,2)
Row 0 has {'5','3','7'}, column 2 has {'8'}, box 0 has {'5','3','6','9','8'}. Candidates are digits not in any of these sets: '1','2','4'. So length is 3.Final Answer:
Option B -> Option BQuick Check:
Counting candidates for (0,2) yields 3 [OK]
- Forgetting box constraints
- Miscounting candidates for first empty cell
Solution
Step 1: Identify the main operations
The algorithm scans from the end to find the pivot (O(n)), then scans again to find the swap element (O(n)), and finally reverses the suffix (O(n)).Step 2: Sum up the operations
All steps are linear scans or swaps, so total time complexity is O(n).Final Answer:
Option A -> Option AQuick Check:
No sorting or factorial generation involved, linear scans only [OK]
- Confusing suffix reversal with sorting
- Assuming factorial due to permutations
Solution
Step 1: Understand reuse requirement
Allowing reuse means digits can be chosen multiple times to build combinations of length n.Step 2: Identify correct approach
Backtracking can be modified to not increment the digit index after choosing a letter, allowing reuse until length n is reached.Step 3: Why other options fail
Iterative queue approach as-is assumes fixed digit positions; DP without reuse does not handle repeated digits; sorting and picking once per digit ignores reuse.Final Answer:
Option A -> Option AQuick Check:
Backtracking with flexible index handles reuse elegantly [OK]
- Trying to reuse digits in iterative approach without index control
- Ignoring reuse in DP or sorting
Solution
Step 1: Analyze relaxed constraints
Column conflicts are ignored, so column bitmask is unnecessary; diagonal conflicts remain.Step 2: Modify bitmask tracking accordingly
Remove column bitmask from conflict checks and recursive calls; keep positive and negative diagonal bitmasks to prune invalid placements.Final Answer:
Option C -> Option CQuick Check:
Removing column mask matches relaxed rules and preserves diagonal conflict checks [OK]
- Ignoring diagonals too
- Allowing all placements without pruning
