All-Different Variants, Revisited
A while back, I compared five implementations of the all-different constraint on generalized NxN Sudokus: Binary, Basic, Sparse, Pigeonhole, and Bipartite. The takeaway back then was a fairly tidy trade-off. Sparse and Basic were fastest on 16x16 grids, Binary dragged under the weight of too many small constraints, Pigeonhole held up reasonably well as grids grew, and Bipartite pulled away on 25x25 and 36x36 with steady, predictable runtimes.
Since then, the solver went through a heavy optimization pass - packing live domains into uint64 bitsets, adding custom propagators, and flattening search state out of Go maps into dense slices - along with targeted rewrites of Bipartite, Sparse, and Binary. I wanted to re-run the original study to see how much faster things got, which conclusions held up, and which ones flipped.
The five variants at a glance
An all-different constraint applies to a group of variables that cannot share values - in Sudoku, each row, column, and sub-grid box is one such group. The five implementations enforce the exact same rule on a complete board, trading off how early they spot dead ends against how much work each check does:
What changed under the hood
Every variant picked up some free speed from the shared engine changes: uint64 bitset live domains, dense integer variable IDs instead of map[*Variable] lookups, lock-free domain checks during search, and a single shared slice for undoing prunings on backtrack. On top of that, three of the five all-different variants were reworked directly while two stayed untouched:
- Bipartite dropped its duplicate
map[int]map[int]booladjacency graph and value-index map. The Hopcroft-Karp matcher now reads edges straight from each variable’s live domain bitset, reuses a single BFS queue slice, and pins a candidate(variable, value)pair in place with no temporary map allocations. Even better,Supported()now returns in constant time whenever the tested pair is already part of the current maximum matching:func (a *allDiffBipartite) Supported(supV *model.Variable, supVal int) bool { if !supV.LiveDomain().Contains(supVal) { return false } varI := a.varIndicies[supV] valI := supVal - a.minVal + 1 if a.bipartiteMatcher.matchingSize == len(a.vs) && a.bipartiteMatcher.pairU[varI] == valI { return true } return a.bipartiteMatcher.runPinned(varI, valI) == len(a.vs) } - Sparse replaced its
claimedValuesmap with a flat slice of counts and implemented the optional customPropagate()method. Instead of search pollingSupported()on every live value of every peer variable, Sparse pushes prunings directly - one bit check per unassigned peer for the single value just assigned:func (a *allDiffSparse) Propagate(changedVar *model.Variable, _ bool, pruner model.ValuePruner) *model.Variable { val, ok := changedVar.AssignedValue() if !ok { return nil } for _, other := range a.vs { if other != changedVar && !other.IsSet() && other.LiveDomain().Contains(val) { if !pruner.PruneFromVar(other, val, changedVar) { return other } } } return nil } - Binary got a quiet fix that turned out to matter a lot. In the 2023 code,
binaryConstraint.Supported(v, val)temporarily calledv.Set(val)anddefer v.Clear()(firing listeners and mutexes on every value check) before running a nested loop over both domains. Now it leaves the variable alone and scans only the other variable’s live domain bitset, stopping at the first valid partner. - Basic and Pigeonhole were not touched. Both still rely on the fallback
Supported()polling loop. Basic still scans every variable in the constraint on each check (with a small closure allocation when a peer has one value left), and Pigeonhole still allocates a freshmap[int]boolon every singleSupported()call.
Before and after on the same hardware
Comparing fresh numbers straight against the 2023 charts would mix software improvements with three years of Go compiler updates and different hardware. To keep the comparison honest, I checked out the exact commit from the original post (225bc42) and ran both versions on the same CPU using Go 1.26 (interleaving the 16x16 variants round-robin so CPU clock changes couldn’t skew ratios between fast and slow runs).
Every single variant got faster, though the gains split cleanly along who got rewritten and who didn’t:
- Binary was the biggest surprise, jumping 24x faster on 16x16 (96 ms down to 4.0 ms) and 25x faster at the 25x25 median (1.38 s down to 56 ms).
- Sparse dropped 11.7x on 16x16 (5.1 ms down to 0.43 ms) and 42x on 25x25 (434 ms down to 10.3 ms, helped along by the tie-breaking shift below; 10.6x with random ties).
- Bipartite sped up 4.8x on 16x16 (76 ms to 16.0 ms), 4.2x on 25x25 (722 ms to 171 ms), and 4.2x on 36x36 (5.49 s to 1.30 s).
- Pigeonhole and Basic, left untouched, picked up roughly 2x from the bitset domains and flattened search state underneath (plus a bonus on 25x25 from a tie-breaking quirk I’ll come back to below - that’s the gap between the blue and amber dots in the chart above).
Comparing performance
The setup
The benchmark setup matches the original post: empty generalized NxN Sudokus solved to the first solution using the DomWDeg variable heuristic, a random value heuristic, and forward checking after each assignment. I ran 1,000 instances per variant on 16x16, 200 per variant on 25x25 (capped at 60 seconds), and 100 each for Bipartite and Pigeonhole on 36x36 (plus 10 capped runs for the three simpler variants and a 20-run peek at 49x49).
16x16 grids
Starting with steps taken, the ordering hasn’t changed, though Bipartite got even cleaner:
Bipartite solves 96.9% of 16x16 boards in exactly 257 steps - zero backtracks, with a worst case of 337 steps across all 1,000 runs. Pigeonhole follows close behind (69.0% zero-backtrack, median 257). Basic (297 median) still takes slightly fewer steps than Binary (339) and Sparse (340), for the same reason as before: Basic checks peers with one remaining live value even before they are assigned, whereas Sparse only triggers on assignment.
Runtime, though, looks quite different from 2023:
- Sparse is now in a league of its own on 16x16: 0.43 ms median, 0.61 ms at the 90th percentile, and 10.2 ms worst case across 1,000 runs. Over 95% of Sparse runs finish under 0.72 ms - more than 20x faster than Bipartite’s median.
- Basic comes in second at 3.75 ms median, though its tail stretches to 121 ms.
- Binary is the big rank-order flip: at 4.00 ms median (31.6 ms max), it jumped right past Bipartite and now sits virtually tied with Basic. In 2023 it was slower than Bipartite (96 ms vs. 76 ms on this machine); once
Supported()stopped mutating variables on every check, evaluating 120 tiny bitset checks turned out to be cheap. - Bipartite sits fourth at 16.0 ms median, still showing that signature vertical wall (p10 to p90 spans 15.0 ms to 17.9 ms).
- Pigeonhole falls to dead last at 47.9 ms median - over 100x slower than Sparse and 3.0x slower than Bipartite - because it still allocates a map on every
Supported()call.
Larger instances (25x25)
On 25x25 grids with a 60-second cap, timeouts are rare across all five variants:
- Sparse: 1/200 runs timed out.
- Binary: 1/200 runs timed out.
- Basic: 0/200 runs timed out (max 48.7 s).
- Bipartite and Pigeonhole: 0/200 timed out.
In step counts, the gap between the two global constraints and the three simpler ones is as stark as ever. Bipartite finishes in 626 steps at the median (82.0% zero-backtrack, worst case 696 steps out of 200 runs!), and Pigeonhole sits right next to it at 634 median. Meanwhile Basic, Binary, and Sparse still wander anywhere from a few thousand steps into the millions.
Runtime tells a much more interesting story than it did in 2023:
- Sparse is so cheap per step now - averaging around 2 million steps per second across the 200 runs - that even when it takes 15,800 steps at the median, it finishes in 10.3 ms (16x faster than Bipartite!). In fact, Sparse beats Bipartite on roughly the fastest 75% of runs. Beyond that, the heavy tail still bites: the 90th percentile shoots up to 0.78 seconds, and the single timeout burned through 155 million steps in 60 seconds without finding a solution.
- Binary now beats Basic at both the median (56.3 ms vs. 80.9 ms) and the 90th percentile (4.62 s vs. 6.17 s), reversing the 2023 result where Binary struggled well behind Basic. Both take nearly the same number of steps (~5k median, ~380k-400k at p90), yet Binary runs more than twice as fast per step (162k vs. 66k steps/sec). Once Binary stopped mutating variables in
Supported(), checking a single partner per binary constraint turned out noticeably cheaper than Basic scanning all 25 variables in the group on every candidate check. - Bipartite is rock solid: all 200 runs finished under 0.19 seconds (171 ms median, 176 ms at p90, 184 ms max). Where the 2023 post noted Bipartite completing steadily in 1.5-2 seconds (722 ms on this CPU), it now finishes in under a fifth of a second.
- Pigeonhole dropped behind every other variant at the median (555 ms - 3.2x slower than Bipartite). It still holds up better than the three simpler variants in the high percentiles (95th percentile is 592 ms, max 1.33 s), just with a much wider gap behind Bipartite than before.
Even larger instances (36x36 and 49x49)
On 36x36 grids, even with a big per-step speedup, the three simpler variants still cannot keep up. Out of 10 runs capped at 60 seconds each:
- Sparse: 6/10 runs timed out (4 solved in 0.42 s, 25.8 s, 35.6 s, and 49.3 s; the timeouts burned up to 72 million steps per minute).
- Binary: 7/10 runs timed out (3 solved in 0.48 s, 1.0 s, and 19.2 s).
- Basic: 9/10 runs timed out (1 solved in 0.74 s).
Even here, Binary still edges out Basic (3/10 vs. 1/10) while Sparse leads the three at 4/10, though none of the three are viable at this size. That leaves Bipartite and Pigeonhole:
On 36x36, Bipartite finishes 100/100 runs in 1.30 seconds median (1.41 s at p90, 1.46 s max), solving 60% of boards in exactly 1,297 steps with zero backtracks and never exceeding 1,542 steps. Pigeonhole solves 100/100 in 4.81 seconds median - now 3.7x slower than Bipartite, compared to ~2.2x slower in the 2023 code - and its tail still gets bumpy, stretching out to 116 seconds on its hardest run (650k steps).
Because 36x36 Bipartite was down to 1.3 seconds, I pushed one size larger to 49x49 (2,401 cells, plotted as the dashed line above). Bipartite solved 20/20 boards in 7.03 seconds median - with the entire 20-run spread fitting between 6.84 s and 7.52 s, and 5 of those 20 boards finishing in exactly 2,402 steps with zero backtracks. That puts 49x49 Bipartite not far behind 36x36 Pigeonhole (4.81 s), and nearly matching what 36x36 Bipartite took in the 2023 code on this CPU (5.49 s). For comparison, three 49x49 runs with Pigeonhole averaged 29.0 seconds.
A surprise side-effect: DomWDeg tie-breaking
If you compare the step-count plots here with the 2023 post, something might jump out at you. The logical strength of Bipartite didn’t change at all - it still checks whether a maximum matching exists - yet on 36x36 its median steps dropped from thousands down to 1,297, with zero backtracks on 60% of runs. How did pure speed optimizations change the search tree?
It came down to a quiet side-effect of flattening search state. In 2023, DomWDegVariableHeuristic iterated over Tracker’s map[*Variable]bool of unbound variables. On an empty Sudoku, many cells tie for the lowest score, so Go’s randomized map iteration acted as accidental random tie-breaking. Once variables moved into a dense slice sorted by name (00x00, 00x01, …), DomWDeg started breaking ties lexicographically - sweeping systematically across rows and blocks instead of jumping randomly around the grid (while still picking random values for each cell).
To separate pure code speedups from that ordering change, I ran an extra set of benchmarks on the current solver with randomized DomWDeg tie-breaking restored:
Two things stand out:
- The zero-backtrack jump really was tie-breaking. Restoring random ties drops Bipartite’s zero-backtrack rates right back to 2023 territory (66.5% on 16x16, 27.0% on 25x25, and 3.3% on 36x36, where median steps jump from 1,297 back up to 4,748 and the worst case reaches 39,351). The simpler variants benefited from deterministic tie-breaking too on 25x25: Sparse’s median dropped from 41.1 ms to 10.3 ms, Binary from 143 ms to 56.3 ms, and Basic from 215 ms to 80.9 ms. Filling an empty Sudoku in a steady row-by-row sweep simply leaves cleaner subproblems than scattering early choices across the board.
- Code optimizations still did the heavy lifting on runtime. Even with randomized ties restored, the current solver is 4.2x faster on 16x16 Bipartite (18.2 ms vs. 76.4 ms), 3.6x faster on 25x25 Bipartite (198 ms vs. 722 ms), and 3.5x faster on 36x36 Bipartite (1.59 s vs. 5.49 s) - along with 10.0x on 16x16 Sparse and 26x on 16x16 Binary. Notice also that taking nearly 4x as many steps on 36x36 Bipartite (4,748 vs. 1,297) only added 22% to median runtime (1.59 s vs. 1.30 s), because most of the matching work happens near the top of the tree when domains are wide, while backtracks happen near the bottom when only a few candidates remain.
Revised takeaways
Re-running the study after tuning reshaped the trade-offs in a few ways I didn’t quite expect:
- Sparse pulled further ahead on small and medium grids. Adding a custom propagator and flat count slice turned Sparse into a blur: sub-millisecond (0.43 ms) on 16x16, and faster than Bipartite on about 75% of 25x25 runs despite taking orders of magnitude more steps. The heavy tail is still there, so it still isn’t a safe pick when consistent runtimes matter or grids get large, though pairing it with restarts would probably carry it surprisingly far on 25x25.
- Binary is no longer the slowpoke of the simple variants. Removing the accidental variable mutations in
Supported()flipped Binary from trailing Bipartite on 16x16 and dragging behind Basic on 25x25 to beating Bipartite on 16x16 and beating Basic on both 25x25 and 36x36. Keeping constraints small and simple actually pays off once the hidden overhead is gone. - Pigeonhole got left behind. Without incremental tracking or a bitset-based union of live domains, allocating a map on every
Supported()call hurts far more now that the rest of the solver is fast. It is now dead last on 16x16, slower than every other variant at the median on 25x25, and nearly 4x slower than Bipartite on 36x36 and 49x49. (Replacing itsmap[int]boolwith a quick bitwise OR across live domain bitsets would probably close a good chunk of that gap!) - Bipartite is even stronger where it counts. Reading directly from live domain bitsets and short-circuiting already-matched pairs gave it a 4x-5x speedup while keeping its flat, predictable CDFs - taking 36x36 down to ~1.3 seconds and making 49x49 comfortable in ~7 seconds.
- Check step counts when optimizing search infrastructure. Swapping a map for a sorted slice wasn’t supposed to change search behavior, yet it quietly handed
DomWDegmuch cleaner tie-breaking on empty grids. Measuring steps alongside wall-clock time caught that right away instead of letting us credit all of it to bitsets.
There is still plenty of room to push further - rewriting Pigeonhole to union bitsets instead of allocating maps, trying Regin’s all-different algorithm so Bipartite can prune all unsupported values in one pass instead of polling Supported() one candidate at a time, or seeing how far restarts carry Sparse on 25x25. For now, though, the old rule of thumb still holds, just with much sharper lines: Sparse when speed on easy/sparse domains wins, Binary if you want dead-simple code that isn’t slow anymore, and Bipartite whenever consistency or problem size matters.