Question presented to candidate: "Place n queens on an n by n chessboard so that no two attack each other. Write a Python function that returns every solution, and then tell me how you would only count them for n up to 12."
What a strong answer should cover:
- Place one queen per row, so a solution is a list
queens[row] = col; this turns nยฒ cells into n decisions. - Backtracking with choose / explore / un-choose, pruning a column as soon as it is attacked.
- O(1) safety checks using three sets: columns,
r - candr + c. - Complexity: O(n!) upper bound on the search, O(n) extra space plus the output; 92 solutions for n = 8.
- Python details: append
queens[:](a copy), usesetorlist[bool]for the taken markers, recursion depth is only n so the default limit of 1000 is not a problem, and the bitmask version needs& fullbecause Python ints never overflow.
Clarifying questions expected:
- Do you want every board (as strings) or only the number of solutions?
- What range of n should I expect? (It decides whether a bitmask counter is worth it.)
Code / implementation expected: Yes โ a recursive solve_n_queens(n) with three sets in Python 3, and optionally a bitmask counter.