Python 3.11+
None is the unassigned sentinel, so the coloring contract uses colors other than None and a symmetric loop-free adjacency list.
Verify in Python docs(opens in a new tab)Maintain a valid partial assignment, reject conflicts before descending, and undo a failed choice. Distinguish a most-constrained-variable heuristic from the coloring Lab's fixed node order.
2 practice exercises12 interview problems
Recognize it when Variables have candidate domains and joint constraints reject some assignments.
Checking your account…
A partial assignment maps some variables to allowed values. A constraint can reject that partial state only when the available information already proves a violation. Graph coloring uses nodes as variables, colors as domains and unequal colors across edges as constraints. A locally allowed color may still leave later nodes with no choice, so committing greedily is insufficient in general.
choose_variable picks the unassigned name with the smallest supplied domain, breaking ties by name. A small domain can reveal failure early. The Lab does not shrink domains itself: its caller must supply the currently applicable domains. Assigned variables must be excluded even if their domains are shortest.
def choose_variable(domains,assigned):
candidates=[name for name in domains if name not in assigned]
return min(candidates,key=lambda name:(len(domains[name]),name)) if candidates else NoneImplement choose_variable(domains,assigned). Variable names are comparable strings and domains are lists. Return the unassigned variable with the smallest supplied domain, breaking ties by variable name, or None if every variable is assigned.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def choose_variable(domains,assigned):
candidates=[name for name in domains if name not in assigned]
return min(candidates,key=lambda name:(len(domains[name]),name)) if candidates else NonePredict choose_variable({"z":[1,2],"b":[2],"a":[1]}, {"a":1}). The assigned a is not a candidate even though its domain is short.
| Step | Executed statement | State | Why |
|---|---|---|---|
| 1 | candidates=[name for name in domains if name not in assigned] |
candidates=["z","b"] |
The assigned name a is removed before the heuristic is evaluated. |
| 2 | key=lambda name:(len(domains[name]),name) |
z key=(2,"z"); b key=(1,"b") |
The domain size is the primary comparison and the name breaks ties. |
| 3 | return min(candidates,key=lambda name:(len(domains[name]),name)) if candidates else None |
return="b" |
The remaining one-value domain is selected without changing any domain or assignment. |
| Output | |
|---|---|
print(choose_variable({"z":[1,2],"b":[2],"a":[1]},{"a":1})) |
b |
This heuristic changes search order, not which assignments are valid. It is a separate illustration: the coloring Lab below uses fixed node order and does not call choose_variable or implement domain propagation.
color_graph tries colors in their given order for each node. A candidate passes only when all adjacent assigned colors differ from it. On a deeper failure, the slot returns to None before the next candidate. On success, it intentionally keeps the completed assignment and returns immediately.
def color_graph(adjacency,colors):
assigned=[None]*len(adjacency)
def search(node):
if node==len(adjacency): return True
for color in colors:
if all(assigned[n]!=color for n in adjacency[node]):
assigned[node]=color
if search(node+1): return True
assigned[node]=None
return False
return assigned if search(0) else []Implement color_graph(adjacency,colors). adjacency is a symmetric loop-free undirected graph with valid node indices, and colors are ordered values other than None. Return the first valid color list in node order using colors order, or [] if no coloring exists.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def color_graph(adjacency,colors):
assigned=[None]*len(adjacency)
def search(node):
if node==len(adjacency): return True
for color in colors:
if all(assigned[n]!=color for n in adjacency[node]):
assigned[node]=color
if search(node+1): return True
assigned[node]=None
return False
return assigned if search(0) else []The graph must be a symmetric, loop-free undirected adjacency list with valid indices, and colors cannot be None because None denotes unassigned. With symmetry, each edge is checked when its later endpoint is assigned. Asymmetric lists can miss an edge after its earlier endpoint was checked; a self-loop is not handled by this forward assignment test. Empty input and failure both return an empty list under this Lab contract.
For n nodes and b colors, worst-case exploration is exponential; neighbor checks add their own cost. Pruning and variable order often reduce practical work, but do not turn the general coloring search into polynomial time. The first success follows node order and supplied color order, not necessarily lexical value order. A two-color feasibility question instead admits a linear graph traversal. For a general constraint search, explain the stopping rule, conflict test and exact restoration before proposing propagation or a different variable heuristic.
Python 3.11+
None is the unassigned sentinel, so the coloring contract uses colors other than None and a symmetric loop-free adjacency list.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Find the first coloring of n nodes with b available colors | O(n*b^n) for b>=2 in the worst case | O(n*b^n) for b>=2 in the worst case | Each attempted color can inspect O(n) neighbors; an unpruned search has exponentially many partial assignments. |
O(n) assignments and recursive frames; choose_variable uses O(U) candidate storage for U unassigned names.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
A short domain does not make an assigned variable eligible for another decision.
Prevent it: Filter assigned names before taking the minimum.
candidates=list(domains)
chosen=min(candidates,key=lambda name:(len(domains[name]),name))candidates=[name for name in domains if name not in assigned]
chosen=min(candidates,key=lambda name:(len(domains[name]),name))Where you will hit this: Build a Unique Assignment(opens in a new tab)
A minimum by length alone keeps the first encountered name, violating the Lab's name tie-break.
Prevent it: Compare the tuple of domain size and variable name.
chosen=min(domains,key=lambda name:len(domains[name]))chosen=min(domains,key=lambda name:(len(domains[name]),name))Where you will hit this: Build a Unique Assignment(opens in a new tab)
any passes if one neighbor is compatible even when another already has the proposed color.
Prevent it: Require all assigned-neighbor constraints to pass.
allowed=any(assigned[neighbor]!=color for neighbor in neighbors)allowed=all(assigned[neighbor]!=color for neighbor in neighbors)Where you will hit this: Reusable-Candidate Combination Sum(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27
hello-interview · checked 2026-07-12