Skip to contentKEEP THE CRAFTTHE SANCTUARY

Constraint Satisfaction

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…

Constraint Satisfaction Code Labs

Separate Variables, Domains and Constraints

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.

Use a Heuristic without Changing the Validity Rule

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.

Trace Most-Constrained Choices

Reference
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 None
Practice

Implement 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.

Public tests

  • Choose minimum remaining values

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Most-Constrained Choices

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 None

Exclude Assigned Names before Comparing Domain Sizes

Predict 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.
Print 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.

Reject a Conflict and Restore a Failed Choice

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.

Solve a Small Graph Coloring

Reference
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 []
Practice

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.

Public tests

  • Respect constraints and restore failures

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Solve a Small Graph Coloring

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.

Describe the Search Boundary in an Interview

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 Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Find the first coloring of n nodes with b available colorsO(n*b^n) for b>=2 in the worst caseO(n*b^n) for b>=2 in the worst caseEach attempted color can inspect O(n) neighbors; an unpruned search has exponentially many partial assignments.

Space

O(n) assignments and recursive frames; choose_variable uses O(U) candidate storage for U unassigned names.

Assumptions

  • For b=1 there is only one candidate path, so work is O(n+E); no colors fail at the first nonempty variable.
  • choose_variable scans names and takes a minimum in O(V), assuming list-domain len and dictionary membership are constant-time.
  • None is the unassigned sentinel, so the coloring contract uses colors other than None and a symmetric loop-free adjacency list.

Invariants Worth Saying Aloud

  1. Before each coloring frame, earlier node assignments satisfy all processed undirected edges.
  2. A proposed color differs from all currently assigned neighbors before recursion starts.
  3. Failure restores the assigned slot to None before another color is tried.
  4. The variable-selection Lab excludes already assigned names and resolves domain-size ties by name.

When To Use Or Avoid Constraint Satisfaction

Use It When

  • A small search space permits backtracking and partial conflicts can be checked cheaply.
  • The output contract specifies first success, all solutions or another stopping rule.

Choose Another Tool When

  • The problem has a proved polynomial specialization, such as two-color feasibility on an undirected graph.
  • A claimed pruning rule only seems unlikely rather than proving that no completion exists.
  • Input sizes make unrestricted exponential enumeration impractical.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Choosing a variable that is already assigned

A short domain does not make an assigned variable eligible for another decision.

Prevent it: Filter assigned names before taking the minimum.

Avoid

candidates=list(domains)
chosen=min(candidates,key=lambda name:(len(domains[name]),name))

Use instead

candidates=[name for name in domains if name not in assigned]
chosen=min(candidates,key=lambda name:(len(domains[name]),name))

Letting insertion order decide a domain-size tie

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.

Avoid

chosen=min(domains,key=lambda name:len(domains[name]))

Use instead

chosen=min(domains,key=lambda name:(len(domains[name]),name))

Accepting a color when only one neighbor differs

any passes if one neighbor is compatible even when another already has the proposed color.

Prevent it: Require all assigned-neighbor constraints to pass.

Avoid

allowed=any(assigned[neighbor]!=color for neighbor in neighbors)

Use instead

allowed=all(assigned[neighbor]!=color for neighbor in neighbors)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.