Recursion and Backtracking Questions
Recursion mechanics (base and recursive cases, tracing call stack frames, what lives on the stack versus the heap, tail calls, recursion depth limits and stack overflow diagnosis, recursion-to-iteration conversion with an explicit stack or trampoline, recursion versus iteration trade-offs) and recursion on nested data and simple divide-and-conquer (Euclid's gcd, string reversal, flattening nested lists and dictionaries lazily with generators, recursive maximum subarray). Also backtracking search over combinatorial spaces: permutations (including duplicates and the k-th permutation), subsets, combinations, combination sum, generating balanced parentheses, N-Queens (with bitmasks and symmetry), Sudoku (with minimum-remaining-values ordering), word search, palindrome partitioning, Knight's Tour and Hamiltonian paths. Covers the choose/explore/undo template, how it differs from plain DFS, state-leakage bugs, pruning, and recursion-tree complexity (O(b^d)) including call-tree counts. Memoized recursion, tree traversals, and general graph search are covered elsewhere.
What does accidental state leakage mean in recursive and backtracking code? Show a concrete Python example (such as a shared list or mutable default argument) that is buggy, fix it, and describe tests that would catch this kind of bug.
Sample Answer
The idea in plain words
State leakage means a piece of data that you meant to be private to one call, one branch or one result is secretly shared with another. In recursive and backtracking code it shows up in three ways, and all three come from Python objects being mutable (changeable in place) and from variables holding references (pointers to the object, not a copy of it).
- A mutable default argument. Python evaluates a default value once, when the
defline runs, not on every call. A default of[]is therefore one list that every call without that argument shares. - An aliased result.
results.append(path)stores a reference to the one livepathlist. Backtracking keeps changingpath, so every stored "result" is the same object and they all show whateverpathholds at the end. - A missing undo. Backtracking follows the pattern choose, explore, undo. If the undo is skipped, a choice made in one branch is still present when a sibling branch runs.
Buggy examples, then fixes
Each buggy function sits next to its fix so the one-line difference is visible.
from itertools import combinations
def count_calls_buggy(items, seen=[]): # the default list is built once, at def time
seen.append(len(items))
return len(seen)
def count_calls_fixed(items, seen=None):
if seen is None:
seen = [] # a fresh list per call
seen.append(len(items))
return len(seen)
print([count_calls_buggy([1]) for _ in range(3)])
print([count_calls_fixed([1]) for _ in range(3)])
def subsets_aliased(nums):
results, path = [], []
def explore(i):
if i == len(nums):
results.append(path) # stores a reference to the one live list
return
path.append(nums[i])
explore(i + 1)
path.pop()
explore(i + 1)
explore(0)
return results
def subsets_no_undo(nums):
results, path = [], []
def explore(i):
if i == len(nums):
results.append(path[:])
return
path.append(nums[i])
explore(i + 1) # missing path.pop()
explore(i + 1)
explore(0)
return results
def subsets(nums):
results, path = [], []
def explore(i):
if i == len(nums):
results.append(path[:]) # snapshot copy
return
path.append(nums[i])
explore(i + 1)
path.pop() # undo exactly what was done
explore(i + 1)
explore(0)
return results
print(subsets_aliased([1, 2]))
print(subsets_no_undo([1, 2]))
print(subsets([1, 2]))
def subsets_sorts_input(nums):
nums.sort() # mutates the caller's list
return subsets(nums)
def test_matches_reference(fn=subsets):
for n in range(7):
nums = list(range(n))
expected = {c for r in range(n + 1) for c in combinations(nums, r)}
got = fn(nums)
assert len(got) == 2 ** n
assert {tuple(s) for s in got} == expected
def test_results_do_not_alias(fn=subsets):
got = fn([1, 2, 3])
assert len({id(s) for s in got}) == len(got)
got[0].append(99)
assert all(99 not in s for s in got[1:])
def test_repeat_calls_agree(fn=count_calls_fixed):
assert fn([1]) == fn([1])
def test_input_untouched(fn=subsets):
nums = [3, 1, 2]
fn(nums)
assert nums == [3, 1, 2]
for test in (test_matches_reference, test_results_do_not_alias,
test_repeat_calls_agree, test_input_untouched):
test()
print("passed:", test.__name__)
for test, buggy in ((test_matches_reference, subsets_aliased),
(test_matches_reference, subsets_no_undo),
(test_results_do_not_alias, subsets_aliased),
(test_repeat_calls_agree, count_calls_buggy),
(test_input_untouched, subsets_sorts_input)):
try:
test(buggy)
print(test.__name__, "missed", buggy.__name__)
except AssertionError:
print(test.__name__, "catches", buggy.__name__)
Output:
[1, 2, 3]
[1, 1, 1]
[[], [], [], []]
[[1, 2], [1, 2], [1, 2, 2], [1, 2, 2]]
[[1, 2], [1], [2], []]
passed: test_matches_reference
passed: test_results_do_not_alias
passed: test_repeat_calls_agree
passed: test_input_untouched
test_matches_reference catches subsets_aliased
test_matches_reference catches subsets_no_undo
test_results_do_not_alias catches subsets_aliased
test_repeat_calls_agree catches count_calls_buggy
test_input_untouched catches subsets_sorts_input
The causes, one line each. Two pieces of syntax in the listings: nonlocal (used in the traced version below) lets an inner function assign to a variable of the enclosing function instead of creating a new local one, and id(x) returns a number that identifies the object x, so two lists with the same id are the same list, not two equal lists.
count_calls_buggyreturns[1, 2, 3]instead of[1, 1, 1]because the defaultseen=[]is the same list on every call. The fix is theNonesentinel (a placeholder value meaning "not supplied"): create the list inside the function.subsets_aliasedreturns four empty lists because all four entries are the same object, and by the endpathis empty again. The fix ispath[:](orlist(path)), which takes a snapshot copy at the moment of recording.subsets_no_undoreturns[1, 2]twice and[1, 2, 2]twice: the choice2was never removed, so later branches start from a pollutedpath. The fix is apath.pop()that exactly reverses the precedingpath.append(...).
Worked trace of the correct version
This trace comes from an instrumented run of the fixed code on [1, 2]. Every "record" stores a copy, and every "undo" restores the state the previous "choose" changed.
def subsets_traced(nums):
results, path = [], []
step = 0
def log(event):
nonlocal step
step += 1
print(f"{step:2} {event:<7} path={path} results={results}")
def explore(i):
if i == len(nums):
results.append(path[:])
log("record")
return
path.append(nums[i])
log("choose")
explore(i + 1)
path.pop()
log("undo")
explore(i + 1)
explore(0)
return results
print(subsets_traced([1, 2]))
Output:
1 choose path=[1] results=[]
2 choose path=[1, 2] results=[]
3 record path=[1, 2] results=[[1, 2]]
4 undo path=[1] results=[[1, 2]]
5 record path=[1] results=[[1, 2], [1]]
6 undo path=[] results=[[1, 2], [1]]
7 choose path=[2] results=[[1, 2], [1]]
8 record path=[2] results=[[1, 2], [1], [2]]
9 undo path=[] results=[[1, 2], [1], [2]]
10 record path=[] results=[[1, 2], [1], [2], []]
[[1, 2], [1], [2], []]
The same trace with the undo missing
Running the same instrumented structure on subsets_no_undo shows where the four wrong lists come from. Nothing ever removes an element, so after step 2 the path is [1, 2] and stays that way into the second explore(i + 1) call at the bottom of the tree.
def subsets_no_undo_traced(nums):
results, path = [], []
step = 0
def log(event):
nonlocal step
step += 1
print(f"{step:2} {event:<7} path={path} results={results}")
def explore(i):
if i == len(nums):
results.append(path[:])
log("record")
return
path.append(nums[i])
log("choose")
explore(i + 1) # missing path.pop()
explore(i + 1)
explore(0)
return results
print(subsets_no_undo_traced([1, 2]))
Output:
1 choose path=[1] results=[]
2 choose path=[1, 2] results=[]
3 record path=[1, 2] results=[[1, 2]]
4 record path=[1, 2] results=[[1, 2], [1, 2]]
5 choose path=[1, 2, 2] results=[[1, 2], [1, 2]]
6 record path=[1, 2, 2] results=[[1, 2], [1, 2], [1, 2, 2]]
7 record path=[1, 2, 2] results=[[1, 2], [1, 2], [1, 2, 2], [1, 2, 2]]
[[1, 2], [1, 2], [1, 2, 2], [1, 2, 2]]
Reading it: steps 1 to 3 go down and record [1, 2]. Where the correct version undoes the 2 (step 4 of the trace above), this one goes straight to the sibling call, which finds path still equal to [1, 2] and records it again (step 4 here). The next sibling at the higher level then appends 2 onto a path that already holds it (step 5, [1, 2, 2]) and records that twice. Every recorded list is correct for the path it saw, so the copy is not the bug; the polluted path is. Four records at the leaves of a two-element problem come out as [1, 2], [1, 2], [1, 2, 2], [1, 2, 2], exactly the lines printed by subsets_no_undo([1, 2]) earlier.
Tests that would catch this kind of bug
The four tests in the program above pass for the fixed code, and the closing loop runs each test against a version with the bug it is meant to catch, so every test is shown failing at least once. Four ideas cover the family:
- Compare with a reference.
itertools.combinationsgives the true set of subsets for every size from 0 to 6. The aliased and no-undo versions fail this immediately. - Check for aliasing directly. The ids of the result lists must all differ, and appending to one result must not change any other. This pinpoints the missing copy: it fails on
subsets_aliased, as the closing loop shows. - Call twice and compare. A function with a leaking default or a module-level accumulator returns something different the second time. Run the same input twice in one process and assert equal outputs; also run a different input in between. The program runs this on
count_calls_buggy, whose two calls disagree. - Check that the input is untouched, and that state returns to its start. Assert the caller's list is unchanged afterwards; the program runs this on
subsets_sorts_input, a version that sorts the caller's list in place. For a hand-rolled undo, a helper can assert thatpathis empty when the top-level call returns.
Small inputs (sizes 0, 1, 2, 3) are enough, because a leak appears as soon as there are two branches or two calls.
Complexity
The fixed subsets runs in O(n * 2^n) time: there are 2^n results and each copy costs up to n. Extra space beyond the output is O(n) for path and the recursion depth of n + 1 frames. The path[:] copy is the price of correctness here, and it is a deliberate cost, not a waste.
Common mistakes
- Using
[],{}orset()as a default argument, including a helper such asdef dfs(i, path=[]). - Believing
path += [x]is a safe copy. It extends the same list in place, whilepath + [x]builds a new list. Passingpath + [x]down the recursion is a valid alternative to append and pop, because each frame then owns its own list. - Putting
path.pop()after areturnor inside a branch that is skipped by an early exit, so the undo does not always run.
Running the code
python3.12 state_leak.py
python3.12 state_leak_trace.py
Standard library only; save each listing under the file name shown.
Flatten an arbitrarily nested list of integers, such as [1, [2, [3, 4], 5], 6], into a generator that yields integers one at a time without building the whole flat list. Show the recursive version, then explain how you would do it iteratively with an explicit stack.
Sample Answer
The idea
Nested lists are a tree: a list is an inner node and an integer is a leaf. Flattening means visiting the leaves left to right. A generator (a function that uses yield to hand back one value at a time and pauses until asked for the next) fits because it produces each integer on demand, so the flat list is never built. The recursive version is natural: for every item, if it is a list, produce everything that list produces (yield from), otherwise yield the integer.
Approach
- Walk the items in order.
- A list item: delegate to a recursive call with
yield from, which passes the inner generator's values straight out. - An integer item:
yieldit. - The iterative version replaces the call stack with your own stack, holding the iterators of the lists currently being walked.
Iterators and StopIteration, in four lines
The iterative version relies on Python's iterator protocol. iter(some_list) returns an iterator, an object that remembers its position in the list; each next(it) returns the following item, and when nothing is left next raises StopIteration, the signal that the sequence is finished. The explicit-stack code below catches that exception to learn that a list is exhausted:
numbers = [7, 8]
it = iter(numbers) # an iterator remembers its position in the list
print(next(it))
print(next(it))
try:
next(it) # nothing left
except StopIteration:
print("StopIteration: the iterator is exhausted")
Output:
7
8
StopIteration: the iterator is exhausted
The code
from typing import Iterator, List, Union
Nested = Union[int, List["Nested"]] # a Nested value is an int or a list of Nested values (the type refers to itself)
def flatten(items: List[Nested]) -> Iterator[int]:
"""Recursive generator: yields integers lazily, left to right."""
for item in items:
if isinstance(item, list):
yield from flatten(item) # hand control to the inner generator
else:
yield item
def flatten_iterative(items: List[Nested]) -> Iterator[int]:
"""Same output with an explicit stack of list iterators instead of the call stack."""
stack = [iter(items)]
while stack:
try:
item = next(stack[-1])
except StopIteration:
stack.pop() # next() raised StopIteration: this list is exhausted, resume its parent
continue
if isinstance(item, list):
stack.append(iter(item)) # go one level down
else:
yield item
data = [1, [2, [3, 4], 5], 6]
print(list(flatten(data)))
print(list(flatten_iterative(data)))
gen = flatten(data)
print(next(gen), next(gen)) # lazy: only two values have been produced so far
edge_cases = [[], [[]], [[], [[]], 7], [[[[1]]]], [0, [-5, [10 ** 20]]]]
for case in edge_cases:
assert list(flatten(case)) == list(flatten_iterative(case))
print(case, "->", list(flatten_iterative(case)))
deep = []
for _ in range(5000):
deep = [deep, 1] # 5000 levels of nesting
print(sum(1 for _ in flatten_iterative(deep)))
try:
sum(1 for _ in flatten(deep))
except RecursionError:
print("recursive version: RecursionError")
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
1 2
[] -> []
[[]] -> []
[[], [[]], 7] -> [7]
[[[[1]]]] -> [1]
[0, [-5, [100000000000000000000]]] -> [0, -5, 100000000000000000000]
5000
recursive version: RecursionError
next(gen) twice returns 1 and 2 and nothing else is computed, which shows the laziness. The 5,000-deep structure at the end, built by repeatedly wrapping, defeats the recursive version (it raises RecursionError, since each level of nesting adds generator frames to the call chain and the default limit is 1000) but not the explicit-stack one.
How the explicit stack works
The stack holds one iterator per open list. Look at the iterator on top: take its next item. If it is a list, push an iterator for it (descend). If it is an integer, yield it. When the top iterator is exhausted, pop it and carry on with its parent, which resumes exactly where it left off, because an iterator remembers its position. This is what the call stack did for you in the recursive version.
Worked trace of [1, [2, [3, 4], 5], 6]
def flatten_iterative_traced(items):
stack = [iter(items)]
while stack:
try:
item = next(stack[-1])
except StopIteration:
stack.pop()
print(f" list exhausted, pop -> stack depth {len(stack)}")
continue
if isinstance(item, list):
stack.append(iter(item))
print(f" enter {item} -> stack depth {len(stack)}")
else:
print(f" yield {item} (stack depth {len(stack)})")
yield item
print(list(flatten_iterative_traced([1, [2, [3, 4], 5], 6])))
Output:
yield 1 (stack depth 1)
enter [2, [3, 4], 5] -> stack depth 2
yield 2 (stack depth 2)
enter [3, 4] -> stack depth 3
yield 3 (stack depth 3)
yield 4 (stack depth 3)
list exhausted, pop -> stack depth 2
yield 5 (stack depth 2)
list exhausted, pop -> stack depth 1
yield 6 (stack depth 1)
list exhausted, pop -> stack depth 0
[1, 2, 3, 4, 5, 6]
Reading it: the stack depth rises to 3 inside [3, 4], shrinks as lists run out, and the values come out in order 1, 2, 3, 4, 5, 6.
Complexity
- Time: each element of the structure is visited once, so O(N) for N integers and lists in total. The iterative version does O(1) amortised work per element of the structure (each integer or list is pushed, yielded or popped once). That is an average over the whole run, not a promise about each value: the work between two yields can be as long as the nesting is deep, because every level has to be pushed or popped on the way. The listing below counts the loop steps for one integer wrapped in
dnested lists, followed by a second integer.
def steps_between_values(depth):
value = [1]
for _ in range(depth):
value = [value]
stack = [iter([value, 2])] # the integer 1 sits `depth` + 1 lists down, then comes 2
steps = []
while stack and len(steps) < 2:
count = 0
while True:
count += 1
try:
item = next(stack[-1])
except StopIteration:
stack.pop()
continue
if isinstance(item, list):
stack.append(iter(item))
else:
break
steps.append(count)
return steps
for depth in (100, 200, 400):
print(depth, steps_between_values(depth))
Output:
100 [102, 102]
200 [202, 202]
400 [402, 402]
Each of the two values takes d + 2 steps, so the time between values grows with d even though the total work stays O(N).
- The recursive generator pays for depth on every value: a value yielded from depth d is passed up through d
yield fromlevels, so asking for the next value resumes every paused generator on the way down to it. The explicit-stack version resumes one generator per value. The listing counts resumed generator frames per value (sys.setprofilereports acallevent each time a paused generator is resumed), for 1000 integers wrapped indepthextra lists:
import sys
def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
def flatten_iterative(items):
stack = [iter(items)]
while stack:
try:
item = next(stack[-1])
except StopIteration:
stack.pop()
continue
if isinstance(item, list):
stack.append(iter(item))
else:
yield item
def resumes_per_value(func, depth):
data = list(range(1000))
for _ in range(depth):
data = [data] # 1000 integers, wrapped in `depth` extra lists
resumes = 0
def count_calls(frame, event, arg):
nonlocal resumes
if event == "call": # also fires each time a paused generator is resumed
resumes += 1
gen = func(data)
next(gen) # first value: pay the descent once
resumes = 0
sys.setprofile(count_calls)
for _ in gen:
pass
sys.setprofile(None)
return resumes / 999
for depth in (1, 10, 100):
print(depth, round(resumes_per_value(flatten, depth), 1), round(resumes_per_value(flatten_iterative, depth), 1))
Output:
1 2.0 1.0
10 11.0 1.0
100 101.1 1.0
The columns are the depth, the recursive version and the explicit-stack version. The recursive form resumes about depth + 1 frames per value and the stack form resumes 1. These counts are one CPython 3.12 measurement.
- Space: O(d) for nesting depth d in both forms (generator frames in one, iterators in the other). The flat list is never built, so memory does not grow with the number of integers.
- Recursion limit: the recursive form fails at roughly the default limit of 1000 nested levels (the 5,000-deep case above). The stack form has no recursion limit; its stack of iterators lives on the heap, and the 5,000-deep case above runs.
Edge cases and common mistakes
- Empty lists anywhere (
[],[[]],[[], [[]], 7]) yield nothing for that part and must not stop the walk. - Negative numbers, zero and very large integers pass through untouched (
[0, [-5, [10**20]]]). - Forgetting
yield fromand writingflatten(item)alone creates a generator and throws it away, so inner values vanish (on[1, [2, [3, 4], 5], 6]only 1 and 6 come out). - Writing
for x in flatten(item): yield xproduces the same values but is wordier thanyield from. - Other iterables: strings are iterable and each character is itself a string, so an
isinstance(item, Iterable)test would recurse untilRecursionErroron"a"(a one-character string yields itself as its only item); testing forlist(or for a list/tuple pair) avoids that. - Mutating the input while a generator is half-consumed changes what the rest of the iteration produces, because the generator reads the live list (appending 9 to
[1, 2, 3]after taking the first value makes the remaining values[2, 3, 9]). Copy the input if that matters.
Follow-ups
- Return a flat list instead:
list(flatten(x)), which uses O(N) extra memory, the cost the generator avoided. - Support tuples and other sequences, or a depth limit parameter (flatten only k levels).
- A nested-iterator class with
next()andhas_next():has_next()must answer yes or no without consuming a value, so the class runs the explicit-stack loop until it finds the next integer, stores it, and reports True;next()hands out the stored value and fetches the following one.
Running the code
Python 3.12, standard library only.
python3 flatten.py ; python3 flatten_trace.py ; python3 flatten_steps.py ; python3 flatten_resumes.py (the main listing, the trace, the step counter and the resume counter; the four-line iterator snippet near the top runs on its own)
A backtracking search enumerates combinations that sum to a target and is too slow. Describe three pruning techniques that cut the explored space and, for each, how it preserves correctness and what it saves.
Sample Answer
The idea in plain words
A backtracking search for "which numbers add up to the target" explores a tree: at each number it either takes it or leaves it, so n numbers give a tree of about 2^n leaves. Pruning means cutting a branch as soon as you can prove no solution lies below it. A good prune is safe (it only removes branches that hold no answer, so the set of answers is unchanged) and cheap (the check costs far less than the subtree it removes).
The three techniques below assume positive numbers, which is what makes each of them safe. Each is shown with a measured effect on one fixed instance.
The three techniques
1. Early validation: stop as soon as the partial choice is already invalid or already complete.
Keep a running remaining = target - sum(chosen) instead of recomputing the sum at the leaf. If remaining < 0, stop: with positive numbers, adding more can only make it worse. If remaining == 0, record the answer and stop, because adding anything else overshoots.
Why it preserves correctness: with positive numbers no solution can lie below an overshooting or an exactly complete node.
What it saves: the entire subtree below every overshoot, and the O(n) re-summing at each leaf.
2. A bounding function: stop when even the best case cannot reach the target.
Precompute suffix[i], the sum of everything from position i onwards. If suffix[i] < remaining, taking every remaining number still falls short, so the branch is dead.
Why it preserves correctness: suffix[i] is the largest total the rest of the search could add (an upper bound: a value the real quantity can never exceed), so if the bound is below what is needed, no choice can succeed.
What it saves: subtrees that look fine under technique 1 (nothing has overshot) but have run out of material. It costs O(n) once to precompute and O(1) per check.
3. An ordering heuristic (a rule of thumb that usually helps but guarantees nothing): try the numbers in the order that makes techniques 1 and 2 fire sooner.
Sort the numbers largest first. Big numbers move remaining the most and use up the suffix total fastest, so both cuts have a chance to fire higher in the tree.
Why it preserves correctness: the order in which the numbers are tried changes which branches die early, not which solutions exist, since every combination is still reachable in some order. The measurement program below asserts that every variant finds the same count as an exhaustive check.
What it saves: it adds no cutting rule of its own; it makes the other two fire earlier in the tree, where each cut removes more.
A tiny instance to trace by hand
Take the numbers [3, 5, 7] and the target 8. The only subset that works is 3 + 5. The program below prints every call as i=<position> remaining=<target still needed>, indented by depth, and says why a call stops. Each rule is switched on in turn.
def trace_search(nums, target, *, early, bound, show=True):
n = len(nums)
suffix = [0] * (n + 1)
for i in range(n - 1, -1, -1):
suffix[i] = suffix[i + 1] + nums[i]
calls = 0
def search(i, remaining, depth):
nonlocal calls
calls += 1
pad = " " * depth
label = f"{pad}i={i} remaining={remaining}"
if early and remaining < 0:
if show: print(label, "-> overshoot, cut")
return
if early and remaining == 0:
if show: print(label, "-> exact hit")
return
if bound and suffix[i] < remaining:
if show: print(label, f"-> suffix[{i}]={suffix[i]} < {remaining}, cut")
return
if i == n:
if show: print(label, "-> out of numbers")
return
if show: print(label)
search(i + 1, remaining - nums[i], depth + 1)
search(i + 1, remaining, depth + 1)
search(0, target, 0)
return calls
print("no pruning, [3, 5, 7], target 8")
print("calls:", trace_search([3, 5, 7], 8, early=False, bound=False))
print("\nearly validation, [3, 5, 7], target 8")
print("calls:", trace_search([3, 5, 7], 8, early=True, bound=False))
print("\nearly validation + bound, [3, 5, 7], target 8")
print("calls:", trace_search([3, 5, 7], 8, early=True, bound=True))
print("\n[2, 3, 4, 5, 12], target 15, smallest first")
print("calls:", trace_search([2, 3, 4, 5, 12], 15, early=True, bound=True, show=False))
print("\n[12, 5, 4, 3, 2], target 15, largest first")
print("calls:", trace_search([12, 5, 4, 3, 2], 15, early=True, bound=True))
Output:
no pruning, [3, 5, 7], target 8
i=0 remaining=8
i=1 remaining=5
i=2 remaining=0
i=3 remaining=-7 -> out of numbers
i=3 remaining=0 -> out of numbers
i=2 remaining=5
i=3 remaining=-2 -> out of numbers
i=3 remaining=5 -> out of numbers
i=1 remaining=8
i=2 remaining=3
i=3 remaining=-4 -> out of numbers
i=3 remaining=3 -> out of numbers
i=2 remaining=8
i=3 remaining=1 -> out of numbers
i=3 remaining=8 -> out of numbers
calls: 15
early validation, [3, 5, 7], target 8
i=0 remaining=8
i=1 remaining=5
i=2 remaining=0 -> exact hit
i=2 remaining=5
i=3 remaining=-2 -> overshoot, cut
i=3 remaining=5 -> out of numbers
i=1 remaining=8
i=2 remaining=3
i=3 remaining=-4 -> overshoot, cut
i=3 remaining=3 -> out of numbers
i=2 remaining=8
i=3 remaining=1 -> out of numbers
i=3 remaining=8 -> out of numbers
calls: 13
early validation + bound, [3, 5, 7], target 8
i=0 remaining=8
i=1 remaining=5
i=2 remaining=0 -> exact hit
i=2 remaining=5
i=3 remaining=-2 -> overshoot, cut
i=3 remaining=5 -> suffix[3]=0 < 5, cut
i=1 remaining=8
i=2 remaining=3
i=3 remaining=-4 -> overshoot, cut
i=3 remaining=3 -> suffix[3]=0 < 3, cut
i=2 remaining=8 -> suffix[2]=7 < 8, cut
calls: 11
[2, 3, 4, 5, 12], target 15, smallest first
calls: 59
[12, 5, 4, 3, 2], target 15, largest first
i=0 remaining=15
i=1 remaining=3
i=2 remaining=-2 -> overshoot, cut
i=2 remaining=3
i=3 remaining=-1 -> overshoot, cut
i=3 remaining=3
i=4 remaining=0 -> exact hit
i=4 remaining=3 -> suffix[4]=2 < 3, cut
i=1 remaining=15 -> suffix[1]=14 < 15, cut
calls: 9
Read it like this.
- No pruning makes 15 calls, the full tree for 3 numbers (2^4 - 1), including three calls that are already below zero (
remaining=-7,remaining=-2andremaining=-4). - Early validation (13 calls). The call
i=2 remaining=0is an exact hit, so it stops and its two child calls never happen (these were theremaining=-7andremaining=0calls, which is why the 13-call run shows only the-2and-4overshoots). The calls withremaining=-2andremaining=-4are cut as overshoots. On three numbers the overshoots sit on the last level, so cutting them saves nothing yet; on a longer list an overshoot near the top removes a whole subtree. - Bounding (11 calls). At
i=2 remaining=8only the number 7 is left (suffix[2]=7), and 7 is less than the 8 still needed, so the branch is dead and its two child calls are skipped. This is a cut that early validation cannot make, because nothing has overshot. - Ordering. On a three-number list the order makes no difference, so the last two runs use
[2, 3, 4, 5, 12]with target 15. Smallest first makes 59 calls. Largest first makes 9, and the trace shows why. Taking 12 leavesremaining=3, so taking 5 overshoots at once and so does 4, and only 3 fits. Leaving 12 out givessuffix[1]=14, which is below 15, so the whole half of the tree that skips 12 is cut at depth 1.
Code and measurement
The counts are recursive calls (not seconds), on 18 numbers drawn with a pinned seed, followed by one hand-built hard case. The two targets show that each technique matters in a different situation: a small target (70) is where overshoot cuts help, and a target near the total (351 out of 376) is where the bound helps.
import random
from itertools import combinations
from typing import List, Tuple
def count_subsets(nums: List[int], target: int, *, early: bool, bound: bool,
descending: bool) -> Tuple[int, int]:
"""Return (number of subsets summing to target, number of recursive calls)."""
nums = sorted(nums, reverse=descending)
n = len(nums)
suffix = [0] * (n + 1) # suffix[i] = sum(nums[i:])
for i in range(n - 1, -1, -1):
suffix[i] = suffix[i + 1] + nums[i]
calls = found = 0
def search(i: int, remaining: int) -> None:
nonlocal calls, found
calls += 1
if early:
if remaining < 0:
return # overshoot: positive numbers cannot reduce it
if remaining == 0:
found += 1 # exact hit: adding anything more would overshoot
return
if bound and suffix[i] < remaining:
return # even taking everything left cannot reach it
if i == n:
if remaining == 0:
found += 1
return
search(i + 1, remaining - nums[i]) # take nums[i]
search(i + 1, remaining) # leave nums[i]
search(0, target)
return found, calls
random.seed(5)
nums = random.sample(range(1, 41), 18)
variants = [
("no pruning", dict(early=False, bound=False, descending=False)),
("1. early validation", dict(early=True, bound=False, descending=False)),
("1+2. add bounding", dict(early=True, bound=True, descending=False)),
("1+2+3. add ordering (largest first)", dict(early=True, bound=True, descending=True)),
]
print("numbers:", sorted(nums), "sum:", sum(nums))
for target in (70, sum(nums) - 25):
truth = sum(1 for r in range(len(nums) + 1)
for c in combinations(nums, r) if sum(c) == target)
print(f"\ntarget {target}: {truth} subsets reach it")
print(f"{'variant':<38}{'found':<8}{'calls'}")
for name, flags in variants:
found, calls = count_subsets(nums, target, **flags)
assert found == truth
print(f"{name:<38}{found:<8}{calls:,}")
# A hard case for all three techniques: every number is even and the target is odd,
# so no subset can reach it, yet neither the overshoot test nor the bound can see that.
even = [2 * i for i in range(1, 19)]
print("\nall-even numbers, odd target 171 (no subset reaches it)")
for descending in (False, True):
found, calls = count_subsets(even, 171, early=True, bound=True, descending=descending)
print(f"{'largest first' if descending else 'smallest first':<38}{found:<8}{calls:,}")
Output:
numbers: [2, 4, 8, 11, 12, 13, 16, 17, 18, 19, 23, 28, 30, 31, 33, 34, 37, 40] sum: 376
target 70: 135 subsets reach it
variant found calls
no pruning 135 524,287
1. early validation 135 24,549
1+2. add bounding 135 24,389
1+2+3. add ordering (largest first) 135 2,569
target 351: 7 subsets reach it
variant found calls
no pruning 7 524,287
1. early validation 7 524,287
1+2. add bounding 7 1,303
1+2+3. add ordering (largest first) 7 135
all-even numbers, odd target 171 (no subset reaches it)
smallest first 0 286,299
largest first 0 35,043
Reading the table
- No pruning always makes 524,287 calls, which is 2^19 - 1: the full tree for 18 numbers.
- For target 70, early validation cuts calls from 524,287 to 24,549 (about 21 times fewer), while the bound adds almost nothing on top (24,389).
- For target 351, early validation saves nothing: in ascending order no partial sum exceeds 351 until the last element, so the overshoot check only fires at the final level. The bound drops calls to 1,303: the target is only 25 below the total of 376, so leaving out numbers worth more than 25 in all makes the target unreachable.
- Largest first cuts the counts again by roughly 9.5 times in both cases (24,389 to 2,569, and 1,303 to 135). That is a result on these two instances, not a guarantee for every input.
Complexity
Without pruning the search is O(2^n) calls, with an O(n) recomputation of the sum per leaf if it is done naively. With the three techniques the worst case is still exponential: subset sum (does any subset reach the target?) is NP-complete, so no pruning rule is known that makes every input fast. An adversarial input is one chosen so that the shortcuts cannot see the dead end. The last two lines of the output show one: eighteen even numbers and an odd target. No subset can work, but no partial sum overshoots early and the suffix bound stays large, so the search still makes 286,299 calls smallest first (more than half of the 524,287 in the full tree) and 35,043 largest first. Ordering helped there, but the count is still far above the 135 to 2,569 calls of the earlier instances. The gains are on typical inputs (an ordering heuristic is a bet on typical inputs, not a proof); the tables above are measured instances, not a bound. Space is O(n) for the recursion depth and the suffix array.
Common mistakes
- Applying the early-validation rules when the list can contain zero or negative numbers. A later negative number could bring the sum back down, so cutting at an overshoot can discard a real answer, and a later zero would still give another answer after an exact hit. With such inputs use only checks that stay valid, or a different method such as dynamic programming.
- Using an upper bound that is not really an upper bound (for example the sum of the next number only). A bound must be at least the true best case, or it cuts live branches.
- Spending more on the check than it saves. A bound that sorts or sums the remaining list at every node costs O(n log n) per node; precompute it once.
- Sorting ascending and expecting early cuts on a target near the total, as the second table shows.
Running the code
python3.12 trace_search.py
python3.12 pruning_ladder.py
Save the first listing as trace_search.py and the second (the one that starts with import random) as pruning_ladder.py. Standard library only.
Implement a backtracking solver in Python that returns all valid N-Queens placements for a given N as lists of strings: def solve_n_queens(n: int) -> List[List[str]]. Explain how you check column and diagonal conflicts efficiently.
Sample Answer
The idea
N-Queens asks for every way to put n queens on an n x n board so that no two attack each other. A queen attacks along its row, its column and both diagonals. The key observation: no two queens may share a row, so a solution has exactly one queen per row. That turns the search into "choose a column for row 0, then for row 1, and so on", which is backtracking: place a queen, recurse to the next row, and if a row has no safe column, undo the last placement and try the next column there.
Brute force and the progression
Choosing any 8 of 64 squares gives 4,426,165,368 placements. Insisting on one queen per row leaves 8^8 = 16,777,216. Insisting that columns differ too leaves 8! = 40,320 permutations. Checking attacks as you go prunes a branch as soon as a conflict appears: the code below makes 2,057 calls (counting the first one) to find all 92 solutions for n = 8 (the calls for n = 8 line in its output).
Checking conflicts in O(1)
Number rows r and columns c from 0. Two squares are on the same "" diagonal exactly when r - c is equal, and on the same "/" diagonal exactly when r + c is equal. Keep three sets: columns used, values of r - c used, values of r + c used. A square is safe if its column, r - c and r + c are in none of the sets, which is three hash lookups. Putting a queen adds to the three sets; removing it on backtrack deletes from them. (Using the sets avoids the negative-index problem that r - c has when you want an array.) For example, (0,0), (1,1) and (2,2) all have r - c = 0, so they lie on one "" diagonal, and (0,3), (1,2), (2,1) and (3,0) all have r + c = 3, so they lie on one "/" diagonal; the first two lines of the demo output below print exactly this.
The code
from typing import List, Optional
def solve_n_queens(n: int, stats: Optional[dict] = None) -> List[List[str]]:
solutions = []
cols = [0] * n # cols[r] = column of the queen in row r
used_col = set()
used_diag = set() # r - c is constant along a "\" diagonal
used_anti = set() # r + c is constant along a "/" diagonal
def place(r: int) -> None:
if stats is not None:
stats["calls"] += 1
if r == n:
solutions.append(["." * c + "Q" + "." * (n - c - 1) for c in cols])
return
for c in range(n):
if c in used_col or (r - c) in used_diag or (r + c) in used_anti:
continue
cols[r] = c
used_col.add(c); used_diag.add(r - c); used_anti.add(r + c)
place(r + 1)
used_col.remove(c); used_diag.remove(r - c); used_anti.remove(r + c)
place(0)
return solutions
def first_n_queens(n: int) -> Optional[List[str]]:
cols = [0] * n
used_col, used_diag, used_anti = set(), set(), set()
def place(r: int) -> bool:
if r == n:
return True
for c in range(n):
if c in used_col or (r - c) in used_diag or (r + c) in used_anti:
continue
cols[r] = c
used_col.add(c); used_diag.add(r - c); used_anti.add(r + c)
if place(r + 1):
return True # stop: leave the state as is, the answer is in cols
used_col.remove(c); used_diag.remove(r - c); used_anti.remove(r + c)
return False
if not place(0):
return None
return ["." * c + "Q" + "." * (n - c - 1) for c in cols]
def count_n_queens(n: int) -> int:
"""Count solutions with three integers used as bit sets instead of three Python sets."""
all_cols = (1 << n) - 1
def place(row: int, cols: int, diag: int, anti: int) -> int:
if row == n:
return 1
total = 0
free = all_cols & ~(cols | diag | anti) # bit c set = column c is safe in this row
while free:
bit = free & -free # lowest safe column
free ^= bit
# going down one row, one diagonal mask moves a bit left and the other a bit right
total += place(row + 1, cols | bit, ((diag | bit) << 1) & all_cols, (anti | bit) >> 1)
return total
return place(0, 0, 0, 0)
for board in solve_n_queens(4):
print("\n".join(board))
print()
for n in range(1, 9):
print(n, len(solve_n_queens(n)))
stats = {"calls": 0}
solve_n_queens(8, stats)
print("calls for n = 8:", stats["calls"])
print(first_n_queens(6))
print(first_n_queens(3))
print([count_n_queens(n) for n in range(1, 11)])
Output:
.Q..
...Q
Q...
..Q.
..Q.
Q...
...Q
.Q..
1 1
2 0
3 0
4 2
5 10
6 4
7 40
8 92
calls for n = 8: 2057
['.Q....', '...Q..', '.....Q', 'Q.....', '..Q...', '....Q.']
None
[1, 0, 0, 2, 10, 4, 40, 92, 352, 724]
solve_n_queens returns every board; for n = 4 there are two, drawn above. first_n_queens stops at the first solution: the recursive function returns True, each caller passes it straight up and returns at once, skipping its undo (harmless here, because the answer is read from cols, which is never cleared). It returns None for n = 2 and n = 3, which have no solution. The counts 1, 0, 0, 2, 10, 4, 40, 92 for n = 1 to 8 match the known values.
The last function, count_n_queens, stores the same three sets as three integers whose bits stand for columns or diagonals. free & -free isolates the lowest set bit (the smallest safe column), and each diagonal mask moves one bit per row. It replaces set lookups with a few bitwise operations and is the usual fast form when only the count is needed; it reproduces the same counts (n = 10 gives 724).
The bit layout on a 4 x 4 board, computed by the demo listing below: column c is bit c, so column 0 is the right-most bit of a 4-bit string. A queen at row 0, column 1 sets cols = 0010. On the next row it attacks column 2 along one diagonal and column 0 along the other, so diag shifts left to 0100 (bit 1 to bit 2) and anti shifts right to 0001 (bit 1 to bit 0). The free squares of row 1 are the bits not set in any of the three masks, 1000, column 3. Placing the queen there gives cols = 1010; diag becomes 1000 (the shifted bits at column 4 fall off the board and & all_cols drops them) and anti becomes 0100, leaving only 0001 free on row 2. The two shifts go opposite ways because the two diagonals move the attacked column in opposite directions as the row increases. free & -free then picks the lowest set bit: -x is the bits of x inverted plus one (two's complement, how negative integers are stored), which keeps the lowest 1 and clears the rest when ANDed with x, so 0110 & -0110 is 0010.
from math import factorial
print("same r - c:", [(r, r) for r in range(3)], "->", {r - r for r in range(3)})
print("same r + c:", [(0, 3), (1, 2), (2, 1), (3, 0)], "->", {r + c for r, c in [(0, 3), (1, 2), (2, 1), (3, 0)]})
n = 4
all_cols = (1 << n) - 1 # 0b1111, column c is bit c (right-most bit = column 0)
cols = diag = anti = 0
bit = 1 << 1 # queen in row 0, column 1
cols |= bit
diag = ((diag | bit) << 1) & all_cols # attacked squares in row 1 on one diagonal: column 2
anti = (anti | bit) >> 1 # attacked squares in row 1 on the other diagonal: column 0
free = all_cols & ~(cols | diag | anti)
print(f"queen at row 0, column 1: cols={cols:04b} diag={diag:04b} anti={anti:04b} free in row 1={free:04b}")
bit = 1 << 3 # queen in row 1, column 3 (the only free square)
cols |= bit
diag = ((diag | bit) << 1) & all_cols # the 1 shifted past column 3 is dropped by & all_cols
anti = (anti | bit) >> 1
free = all_cols & ~(cols | diag | anti)
print(f"queen at row 1, column 3: cols={cols:04b} diag={diag:04b} anti={anti:04b} free in row 2={free:04b}")
x = 0b0110
print(f"x={x:04b} -x (4 bits)={-x & 0b1111:04b} x & -x={x & -x:04b}")
terms, ways = [], 1 # level k of the tree has at most n!/(n-k)! calls
for k in range(n + 1):
terms.append(ways)
ways *= n - k
print("call ceiling for n = 4:", " + ".join(map(str, terms)), "=", sum(terms), f"(complete boards at most {factorial(4)})")
Output:
same r - c: [(0, 0), (1, 1), (2, 2)] -> {0}
same r + c: [(0, 3), (1, 2), (2, 1), (3, 0)] -> {3}
queen at row 0, column 1: cols=0010 diag=0100 anti=0001 free in row 1=1000
queen at row 1, column 3: cols=1010 diag=1000 anti=0100 free in row 2=0001
x=0110 -x (4 bits)=1010 x & -x=0010
call ceiling for n = 4: 1 + 4 + 12 + 24 + 24 = 65 (complete boards at most 24)
Worked trace for n = 4
def trace_n_queens(n):
cols = [0] * n
used_col, used_diag, used_anti = set(), set(), set()
def place(r):
if r == n:
print(f"{' ' * r}solution: columns {cols}")
return
tried = 0
for c in range(n):
if c in used_col or (r - c) in used_diag or (r + c) in used_anti:
continue
tried += 1
print(f"{' ' * r}row {r}: place column {c}")
cols[r] = c
used_col.add(c); used_diag.add(r - c); used_anti.add(r + c)
place(r + 1)
used_col.remove(c); used_diag.remove(r - c); used_anti.remove(r + c)
if tried == 0:
print(f"{' ' * r}row {r}: no safe column, backtrack")
place(0)
trace_n_queens(4)
Output:
row 0: place column 0
row 1: place column 2
row 2: no safe column, backtrack
row 1: place column 3
row 2: place column 1
row 3: no safe column, backtrack
row 0: place column 1
row 1: place column 3
row 2: place column 0
row 3: place column 2
solution: columns [1, 3, 0, 2]
row 0: place column 2
row 1: place column 0
row 2: place column 3
row 3: place column 1
solution: columns [2, 0, 3, 1]
row 0: place column 3
row 1: place column 0
row 2: place column 2
row 3: no safe column, backtrack
row 1: place column 1
row 2: no safe column, backtrack
Reading it: with the first queen in column 0, column 2 in row 1 leaves row 2 with no safe square, so the code backs up; column 3 in row 1 then column 1 in row 2 leaves row 3 stuck, so it backs up to row 0. A queen in column 1 of row 0 leads straight to the solution [1, 3, 0, 2]. Column 2 gives its mirror image [2, 0, 3, 1]. Column 3 dead-ends, matching the two boards printed earlier.
Complexity
- Time: the columns already used are never offered again, so row k has at most n - k choices left. At most n!/(n-k)! calls sit at depth k, so at most 1 + n + n(n-1) + ... + n! calls in total (a ceiling of 65 for n = 4, where the demo above prints it), and at most n! of them are complete boards. That sum is below e x n!, so the search is O(n!). The ceiling also holds at tiny sizes: n = 1 makes 2 calls (ceiling 1 + 1 = 2) and n = 2 makes 3 (ceiling 1 + 2 + 2 = 5), so a plain "at most n! calls" would be wrong there. In practice far fewer calls happen because diagonals prune too (2,057 calls for n = 8 against 40,320 permutations). The number of solutions itself grows quickly (92 for n = 8, 724 for n = 10), and building each output costs O(n^2) characters.
- Space beyond the output: O(n) for the recursion (depth n), the
colslist and the three sets.
Edge cases and common mistakes
- n = 1 returns one board
['Q']; n = 2 and 3 return an empty list. - Forgetting to remove the entries from all three sets on backtrack leaves phantom attacks (squares that still look attacked by a queen that has already been taken off).
- Mixing up the two diagonals (using r + c for both) accepts attacked squares.
- Rescanning the whole board to test safety costs O(n) per square instead of O(1).
- In the early-stop version, ignoring the value the recursive call returns and carrying on with the loop makes the search continue past the first solution and overwrite
cols, so the function ends up returningNoneeven though a solution exists (for n = 6 as well). Undoing the three sets before returningTrueis harmless, becausecolsis never cleared.
Follow-ups
- Count only: the bitmask form above, or use mirror symmetry (flipping a solution left to right gives another solution) to search only half the first row.
- A very large n (a single solution, not all): constructive patterns (closed-form rules that write down a valid placement) or a min-conflicts search (start from a random board, then repeatedly pick a queen that is under attack and move it within its row to the square with the fewest attackers) find one without full backtracking.
- Placing other pieces: only the attack test changes (a knight's test is a fixed list of offsets).
Running the code
Python 3.12, standard library only.
python3 n_queens.py (first listing)
python3 n_queens_demo.py (second listing)
python3 n_queens_trace.py (third listing)
Design and implement a solver for the Knight's Tour on an N x N board using backtracking. Describe how you choose the next move to keep branching low, where that approach can fail, and what you fall back to.
Sample Answer
The idea in plain words
A knight's tour is a walk of knight moves that visits every square of an N x N board exactly once. Backtracking builds it one square at a time: from the current square, try a legal move to an unvisited square, and if the walk later gets stuck, undo moves (backtrack) and try another. The search space is enormous (up to 8 choices per step over N x N steps), so the order in which you try moves decides everything.
The standard order is Warnsdorff's rule, a heuristic (a rule of thumb that usually works but comes with no guarantee): always move to the square that has the fewest onward moves (the fewest unvisited squares a knight could reach from it). The intuition is that squares with few exits are the ones most likely to be stranded later, so you visit them while you still can, and you leave the well-connected squares (which stay reachable from many directions) for last.
Brute force and why it is not enough
Plain backtracking with a fixed move order (the same eight offsets every time) has no idea which squares are at risk. After a poor early choice it can spend an enormous number of nodes exploring a region that can no longer be completed, before it ever revisits the choice that doomed it. Warnsdorff ordering makes most boards almost linear: the walk usually finishes with no backtracking at all.
Approach
- Precompute, for every square, the list of squares a knight can reach (
nbrs), and keep a live countonward[w]of unvisited neighbours of each square. Entering a square decreasesonwardfor its neighbours by one; leaving it restores them. That makes "fewest onward moves" an O(1) lookup instead of a recount. - At each step, collect the unvisited neighbours and sort them by
onward. Drop a candidate withonward == 0unless it is the final square (it would be a dead end). - Recurse on each candidate in that order; if the recursion fails, leave the square and try the next one (this is the backtracking).
- Budget each run: give up as soon as the count of squares entered passes 4 N^2. The check runs just after a square is entered, so a run that fails enters 4 N^2 + 1 squares. A run that never backtracks enters exactly N^2 squares, so the budget allows about three times that much extra searching. The factor 4 is a tuning choice, not a derived value: it leaves room for local repairs (the 8x8 run from (2, 4) below needs 98 squares, about 1.5 N^2) and caps the cost of a run that has gone wrong. A run that is thrashing near the end is almost always paying for a mistake made much earlier, which more local backtracking cannot fix.
- Fall back to restarts: re-run the same search with the ties (squares with equal
onward) broken at random from a seeded generator (a random number generator started from a fixed seed, so every run repeats exactly). A tie-break is the rule that chooses between equally good options. Each restart is cheap, and a different tie-break usually avoids the mistake. In the code,options.sort(key=...)is a stable sort, meaning items with equal keys keep their original order, so without shuffling the ties always resolve the same way. - Reject boards and starts that cannot work before searching. An open tour is a walk that visits every square once and may end anywhere (a closed tour must also end a knight move from where it started). No open tour exists on 2x2, 3x3 or 4x4 boards. On an odd board the knight alternates colours, so it has to start on the colour that has one more square than the other (the corner colour, where row + col is even); the 5x5 picture below shows why.
Where Warnsdorff fails, measured
Warnsdorff's rule has no guarantee. The output below compares the pure rule (take the first best move, never backtrack) with the full search. The columns are: board is N; start is the (row, column) the knight starts on; pure rule reaches is how many squares the pure rule visited before it was stuck; attempts is how many runs of the full search were needed to find a tour; squares entered is the total number of squares entered across all those runs.
Code
import random
import sys
KNIGHT_MOVES = [(2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1)]
def build_neighbors(n):
"""nbrs[square] = squares a knight can reach; square = row * n + col."""
nbrs = [[] for _ in range(n * n)]
for r in range(n):
for c in range(n):
for dr, dc in KNIGHT_MOVES:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n:
nbrs[r * n + c].append(nr * n + nc)
return nbrs
def attempt(n, nbrs, start, rng, node_limit, shuffle_ties):
"""One backtracking run, trying moves in Warnsdorff order.
Returns (path or None, squares_entered). A run gives up as soon as the squares entered
pass node_limit (so it enters at most node_limit + 1), instead of thrashing forever.
"""
total = n * n
onward = [len(x) for x in nbrs] # unvisited neighbours of each square
visited = [False] * total
path = []
nodes = 0
class OutOfBudget(Exception):
pass
def enter(sq):
visited[sq] = True
path.append(sq)
for w in nbrs[sq]:
onward[w] -= 1
def leave(sq):
for w in nbrs[sq]:
onward[w] += 1
path.pop()
visited[sq] = False
def extend(sq):
nonlocal nodes
nodes += 1
if nodes > node_limit:
raise OutOfBudget
if len(path) == total:
return True
last_step = len(path) == total - 1
# a square with no onward move is a dead end unless it is the final square
options = [w for w in nbrs[sq] if not visited[w] and (onward[w] > 0 or last_step)]
if shuffle_ties:
options.sort(key=lambda w: (onward[w], rng.random()))
else:
options.sort(key=lambda w: onward[w]) # stable: ties keep move-list order
for w in options:
enter(w)
if extend(w):
return True
leave(w)
return False
enter(start)
try:
ok = extend(start)
except OutOfBudget:
return None, nodes
return (list(path) if ok else None), nodes
def knights_tour(n, start=(0, 0), seed=0, restarts=50):
"""Open knight's tour from `start`. Returns (list of (row, col) or None, report dict)."""
if n == 1:
return [(0, 0)], {"attempts": 1, "squares": 1}
if n in (2, 3, 4):
return None, {"reason": "no open tour exists on this board"}
if n % 2 == 1 and (start[0] + start[1]) % 2 == 1:
return None, {"reason": "odd board: a tour must start on the majority colour"}
nbrs = build_neighbors(n)
rng = random.Random(seed)
s = start[0] * n + start[1]
squares = 0
for k in range(restarts):
# attempt 0: the deterministic Warnsdorff order; later attempts shuffle ties
path, nodes = attempt(n, nbrs, s, rng, node_limit=4 * n * n, shuffle_ties=k > 0)
squares += nodes
if path:
return [(sq // n, sq % n) for sq in path], {"attempts": k + 1, "squares": squares}
return None, {"reason": "gave up", "squares": squares}
def pure_warnsdorff_reach(n, start):
"""Squares visited by the pure rule (first-best move, no backtracking) before it is stuck."""
nbrs = build_neighbors(n)
onward = [len(x) for x in nbrs]
visited = [False] * (n * n)
sq = start[0] * n + start[1]
visited[sq] = True
for w in nbrs[sq]:
onward[w] -= 1
count = 1
while count < n * n:
options = [w for w in nbrs[sq] if not visited[w]]
if not options:
break
sq = min(options, key=lambda w: onward[w]) # min() keeps the first of equal values
visited[sq] = True
count += 1
for w in nbrs[sq]:
onward[w] -= 1
return count
def show_first_choices(n, start, steps):
"""Print each option and its onward-move count for the first few steps of the pure rule."""
nbrs = build_neighbors(n)
onward = [len(x) for x in nbrs]
visited = [False] * (n * n)
sq = start[0] * n + start[1]
visited[sq] = True
for w in nbrs[sq]:
onward[w] -= 1
for step in range(2, steps + 2):
options = [w for w in nbrs[sq] if not visited[w]]
shown = ", ".join(f"({w // n},{w % n}):{onward[w]}" for w in options)
here = (sq // n, sq % n)
sq = min(options, key=lambda w: onward[w])
print(f"move {step} from {here}: options (square:onward) {shown} -> ({sq // n},{sq % n})")
visited[sq] = True
for w in nbrs[sq]:
onward[w] -= 1
def check_tour(n, tour):
assert len(tour) == n * n and len(set(tour)) == n * n
for (r1, c1), (r2, c2) in zip(tour, tour[1:]):
assert sorted((abs(r1 - r2), abs(c1 - c2))) == [1, 2]
if __name__ == "__main__":
sys.setrecursionlimit(10_000) # the search recurses once per square (up to 2,500)
print("board start pure rule reaches attempts squares entered")
for n, start in [(5, (0, 0)), (8, (0, 0)), (8, (2, 4)), (30, (0, 4)), (50, (0, 6))]:
tour, report = knights_tour(n, start)
check_tour(n, tour)
reach = pure_warnsdorff_reach(n, start)
print(f"{n:4d} {str(start):7s} {reach:5d} of {n * n:<5d} {report['attempts']:5d} {report['squares']:10d}")
for n, start in [(2, (0, 0)), (3, (0, 0)), (4, (0, 0)), (5, (0, 1))]:
print(f"n={n} start={start}:", knights_tour(n, start)[1]["reason"])
print("n=1:", knights_tour(1)[0])
print("pure rule on 5x5 from (0, 0), first three moves:")
show_first_choices(5, (0, 0), 3)
tour, _ = knights_tour(5, (0, 0))
grid = [[0] * 5 for _ in range(5)]
for step, (r, c) in enumerate(tour, 1):
grid[r][c] = step
print("5x5 tour from (0, 0), move numbers:")
for row in grid:
print(" ".join(f"{v:2d}" for v in row))
Run in a python:3.12 container, it prints:
board start pure rule reaches attempts squares entered
5 (0, 0) 25 of 25 1 25
8 (0, 0) 64 of 64 1 64
8 (2, 4) 60 of 64 1 98
30 (0, 4) 844 of 900 2 4501
50 (0, 6) 2226 of 2500 2 12501
n=2 start=(0, 0): no open tour exists on this board
n=3 start=(0, 0): no open tour exists on this board
n=4 start=(0, 0): no open tour exists on this board
n=5 start=(0, 1): odd board: a tour must start on the majority colour
n=1: [(0, 0)]
pure rule on 5x5 from (0, 0), first three moves:
move 2 from (0, 0): options (square:onward) (2,1):5, (1,2):5 -> (2,1)
move 3 from (2, 1): options (square:onward) (4,2):3, (3,3):3, (1,3):3, (0,2):3, (4,0):1 -> (4,0)
move 4 from (4, 0): options (square:onward) (3,2):5 -> (3,2)
5x5 tour from (0, 0), move numbers:
1 22 11 16 7
12 17 8 21 10
25 2 23 6 15
18 13 4 9 20
3 24 19 14 5
Reading the output
- On 8x8 from (0, 0) the pure rule finishes (64 of 64). From (2, 4) it stalls at 60 squares, but backtracking in Warnsdorff order repairs the dead end within the first run, entering 98 squares in total.
- On 30x30 from (0, 4) the first run passes its budget of 4 x 900 = 3,600 squares when it enters square 3,601, and gives up. The second run (tie-breaks shuffled) succeeds, so the total is 3,601 + 900 = 4,501 squares entered. On 50x50 from (0, 6) the same pattern gives 10,001 + 2,500 = 12,501 squares entered.
- The tiny boards (N = 2, 3, 4) are rejected before any search, and N = 1 returns its single square. Without the colour check, an exhaustive search of 5x5 from (0, 1) has to enter over a million squares before concluding that nothing exists (the same
attemptcall with the squares-entered budget lifted enters 1,102,265 of them). - The first moves on 5x5 show the rule: from (2, 1) the square (4, 0) has only one onward move while its siblings have three, so it is taken first; leaving it for later would risk stranding it.
Two facts on real runs: the board colours and the restarts
On a chessboard colouring, the colour of square (row, col) follows the parity of row + col, and every knight move changes row + col by an odd amount (1 + 2 or 2 + 1, possibly negated), so it always lands on the other colour. A 25-square tour therefore visits colours in the order start colour, other, start, other, and so on, which puts 13 squares on the start colour and 12 on the other. The first program prints the 5x5 colouring and the counts, then compares one run with the fixed tie order against runs with random tie-breaks on the 30x30 board from the table above (it imports the listing saved as knights_tour.py):
import sys
sys.setrecursionlimit(10_000)
import random
from knights_tour import attempt, build_neighbors
# Part 1: the two colours of a 5 x 5 board, by (row + col) parity.
n = 5
print("5x5 board, E = row + col even, O = row + col odd")
for r in range(n):
print(" ".join("E" if (r + c) % 2 == 0 else "O" for c in range(n)))
even = sum(1 for r in range(n) for c in range(n) if (r + c) % 2 == 0)
print("even squares:", even, "odd squares:", n * n - even)
# Part 2: restarts with random tie-breaks on 30 x 30 from (0, 4); the budget is 4 * 30 * 30 squares entered.
n, start = 30, (0, 4)
nbrs = build_neighbors(n)
s = start[0] * n + start[1]
print("\n30x30 from (0, 4), a run gives up once it has entered more than 3600 squares")
path, entered = attempt(n, nbrs, s, random.Random(0), 4 * n * n, False)
print("fixed tie order: " + ("tour found" if path else "gave up") + f" after entering {entered} squares")
for seed in range(8):
path, entered = attempt(n, nbrs, s, random.Random(seed), 4 * n * n, True)
print(f"seed {seed}: " + ("tour found" if path else "gave up") + f" after entering {entered} squares")
Output:
5x5 board, E = row + col even, O = row + col odd
E O E O E
O E O E O
E O E O E
O E O E O
E O E O E
even squares: 13 odd squares: 12
30x30 from (0, 4), a run gives up once it has entered more than 3600 squares
fixed tie order: gave up after entering 3601 squares
seed 0: tour found after entering 900 squares
seed 1: tour found after entering 900 squares
seed 2: tour found after entering 900 squares
seed 3: tour found after entering 900 squares
seed 4: tour found after entering 900 squares
seed 5: tour found after entering 900 squares
seed 6: tour found after entering 900 squares
seed 7: tour found after entering 900 squares
The 5x5 board has 13 even squares and 12 odd squares, so a tour must start on an even one such as the corner (0, 0); start (0, 1) is odd and is rejected. A closed tour is a cycle, and a cycle that alternates between two colours needs equal numbers of each, so it has to have an even number of squares; an odd N has N x N squares, an odd number, which is why closed tours need even N.
The fixed tie order gives up after 3,601 squares, matching the table, while each of the eight seeds finds a tour on its first try with exactly 900 squares entered, no backtracking at all. A tie is the first move of the 5x5 trace above: from (0, 0) the options (2,1) and (1,2) both have 5 onward moves, and the fixed order always takes (2,1); a shuffled order may take (1,2), and that different early choice is what avoids the mistake.
Complexity
- Per run: choosing the next square means sorting at most 8 candidates, a constant amount of work (written O(8 log 8) = O(1)), because
onwardis maintained incrementally. A run that never fails costs O(N^2) time. The recursion is one frame per visited square, so the extra space is O(N^2) for the path, visited flags and the recursion stack (that is why the driver raises Python's recursion limit; the default of about 1,000 frames is below the 2,500 squares of a 50x50 board). - With the budget, one run enters at most 4 N^2 + 1 squares, so a restart loop of R runs is O(R N^2) time. The worst case of unbounded backtracking is still exponential, and no bound on R is guaranteed; the fallback is a heuristic that worked on the cases shown, not a proof.
- For a hard guarantee, constructive methods exist: split the board into pieces, build a tour on each piece, and patch them together, which builds tours in time linear in the number of squares. Background reading: Cull and De Curtins, "Knight's Tour Revisited" (Fibonacci Quarterly 16(3), 1978, from page 276) shows that a tour exists on every rectangular board whose smaller side is at least 5 and builds them by divide and conquer, and Parberry, "An Efficient Algorithm for the Knight's Tour Problem" (Discrete Applied Mathematics 73, 1997, pages 251-260) gives a divide-and-conquer construction whose running time is linear in the number of squares.
Edge cases and common mistakes
- N = 1 returns the single square; N = 2, 3 and 4 have no open tour; the open tour of N = 1 is the single square, open tours exist for every N >= 5, and closed tours (the last square a knight move from the first) exist only for even N >= 6, for the reason given with the colour picture. Closed tours need an extra check on the last step: it must be adjacent to the start.
- Odd N with a start whose row + col is odd cannot work; searching it anyway is a very expensive way to learn that.
- Forgetting to restore
onwardon backtrack silently corrupts every later choice. - Treating
onward == 0as the best candidate (fewest exits) walks straight into a dead end; it is only valid on the last square. - Sorting with a fixed tie-break everywhere makes a failure repeat identically on every restart.
Running the code
Save the listing as knights_tour.py and run python knights_tour.py with Python 3.12 and no packages; save the colour and restart program as tie_demo.py in the same folder and run python tie_demo.py. The seed is fixed, so the output is repeatable.
Unlock Full Question Bank
Get access to all 44 Recursion and Backtracking interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.