Practice
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
n?Solution
Step 1: Identify the search space
The algorithm explores permutations of n numbers, which is n! in worst case.Step 2: Consider pruning and bitmask usage
Bitmask helps track used numbers efficiently, pruning invalid branches but the total number of recursive calls is proportional to n * n! because for each position, up to n choices are tried.Final Answer:
Option A -> Option AQuick Check:
Backtracking explores permutations with n choices per position, leading to O(n * n!) complexity [OK]
- Confusing bitmask with exponential 2^n complexity
- Assuming polynomial due to pruning
nxn board?Solution
Step 1: Identify branching factor per row
Each row places one queen in a column not attacked by previous queens, reducing choices roughly by one each time.Step 2: Calculate total recursive calls
Thus, total calls approximate n x (n-1) x (n-2) x ... = n! permutations.Final Answer:
Option D -> Option DQuick Check:
Backtracking prunes invalid columns, yielding O(n!) complexity [OK]
- Confusing bitmask ops with exponential subsets
- Assuming polynomial due to pruning
Solution
Step 1: Understand naive complexity
Brute force backtracking tries up to 9 choices per empty cell, so O(9^m).Step 2: Effect of constraint propagation and heuristics
Pruning reduces branching factor significantly, but worst case remains exponential in m.Final Answer:
Option C -> Option CQuick Check:
Heuristics improve average case but worst-case exponential remains [OK]
- Assuming polynomial or linear time due to heuristics
- Confusing average and worst-case complexities
Solution
Step 1: Identify branching factor per recursion
From each cell, first character has 4 directions, subsequent steps have at most 3 (excluding the cell we came from).Step 2: Calculate total complexity
For each of N cells, explore up to 3^L paths, so total time is O(N * 3^L).Final Answer:
Option B -> Option BQuick Check:
3^L accounts for pruning revisits, not 4^L [OK]
- Assuming 4^L for all steps
- Confusing L with N in complexity
