Multithreaded Shortest-Path Search for a Wheel Combination Lock
System DesignModel answerLast updated
Design a thread-parallel breadth-first search that finds the fewest moves to open a multi-wheel combination lock, covering work splitting, safe visited tracking, level ordering and trade-offs.
Scaling up a combination-lock search
Consider a combination lock with several wheels. Each wheel shows a digit from 0 to 9 and wraps around, so 9 followed by one more forward turn gives 0, and 0 turned backward gives 9. The lock starts at 0000. A single move turns exactly one wheel one step in either direction. A given list of dead-end combinations is forbidden: if the lock ever reaches one, it jams and that path is unusable. You are given a target combination and must find the minimum number of moves to reach it, or report that it is unreachable.
A single-threaded BFS solves the standard 4-wheel version easily. Now suppose you have multiple CPU cores available and the lock has many more wheels.
Your task: describe how you would parallelize this BFS across threads. Your answer should cover:
- Whether parallelism is even worthwhile, and at what problem size.
- How to split the search work among threads, and how to keep BFS level ordering correct.
- How to build a thread-safe visited set and the queues or frontiers, so that no state is explored twice.
- The edge cases: start or target is a dead end, start equals target, unreachable target.
- The trade-offs: lock or atomic contention, memory overhead, load balance, and determinism of the result (distance versus path).
Include a short code sketch if it helps, and state your assumptions about the environment (shared-memory threads versus distributed workers).
Hints
Hint 1
Estimate the state count first. 4 wheels give 10,000 states, which is tiny. Think about how many wheels it takes before thread overhead is worth paying.
Hint 2
Because every move costs 1, correctness only requires that level d is fully finished before level d+1 begins. Think about a barrier between levels and thread-local buffers for newly found states.
Hint 3
To prevent duplicates, either claim each state with an atomic compare-and-swap on a shared visited array, or assign every state a single owning thread so only that thread ever touches its visited flag.
Hint 4
Separate what is deterministic (the distance) from what is not (frontier order, parent pointers), and think about what you would do if a reproducible path were required.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarify first
- Scale. With 4 wheels there are 10^4 states with 8 neighbors each, about 80K edge checks. A sequential BFS takes well under a millisecond, so thread startup and barriers would cost more than they save. I would keep that case sequential.
- Where parallelism pays. With
nwheels there are 10^n states and 2n neighbors each. At n = 8 that is 10^8 states, where multiple cores help. - Output. Is only the distance needed, or also the path? Must the path be reproducible? This determines how much synchronization is needed.
- Environment. I assume shared-memory threads and mention distributed workers as an extension.
Core design: level-synchronous BFS
Since all edges have weight 1, the answer is the level at which the target is first discovered. The simplest way to preserve level ordering is to process one level at a time with a barrier between levels.
- The frontier
F_dholds all states at distanced. - Split
F_damong T threads using dynamic chunking: an atomic counter from which threads grab chunks of roughly 256 to 1024 states. This balances uneven work better than static splits. - Each thread expands its states, generates neighbors, and tries to claim each unvisited one. Claimed states go into a thread-local next-frontier buffer, so there is no shared queue to contend on.
- At the barrier, merge the local buffers into
F_{d+1}. A prefix sum over buffer sizes lets each thread copy into its own slice in parallel. - If the target was claimed in level d+1, return d+1. All states found in one level share the same distance, so stopping is safe. A shared
foundflag lets other threads exit early.
State encoding. Store each state as an integer in [0, 10^n) and compute neighbors with digit arithmetic. This avoids string allocation in the hot loop.
Edge cases. If start or target is a dead end, return -1. If start equals target, return 0. If the frontier becomes empty without finding the target, return -1.
Thread-safe visited set
Option A: shared atomic array. Use a dense array indexed by state. A thread claims a neighbor only if compare_and_swap(visited[s], 0, 1) succeeds. Exactly one thread wins, so each state enters the next frontier once.
- A bitset takes 10^8 bits, about 12.5 MB, but needs
fetch_oron 64-bit words, so 64 states share one contended word. A byte array takes about 100 MB but has less contention per word. - Do a plain read before the CAS (
if visited[s]: skip). In later levels most neighbors are already visited, so this avoids most atomic operations. - Pre-mark dead ends as visited so they are never claimed.
Option B: ownership partitioning. Assign each state to an owner, for example s mod T or a hash. In phase one, each thread routes the neighbors it generates into per-owner outboxes. After a barrier, each owner deduplicates its inbox against its private visited partition. Only one thread ever touches a state's flag, so no atomics are needed.
This costs an extra pass and some buffer memory, but it scales cleanly and extends to multiple machines, where the outboxes become network messages.
Direction optimization. When the frontier covers a large part of the graph, switch to bottom-up. Each owner scans its unvisited states and checks whether any neighbor is in the frontier. Writes stay exclusive, and far fewer edges are touched in the middle levels.
Sketch (ownership partitioning)
In CPython the GIL prevents real CPU speedup, so production code would use processes with shared memory, or C++, Java or Go. The structure is the same.
from concurrent.futures import ThreadPoolExecutor
def open_lock_parallel(deadends, target, wheels=4, workers=4):
dead = {int(d) for d in deadends}
start, goal = 0, int(target)
if start in dead or goal in dead:
return -1
if start == goal:
return 0
T = workers
visited = [set() for _ in range(T)]
for d in dead:
visited[d % T].add(d)
visited[start % T].add(start)
frontier = [[] for _ in range(T)]
frontier[start % T].append(start)
def neighbors(s):
p = 1
for _ in range(wheels):
d = (s // p) % 10
base = s - d * p
yield base + ((d + 1) % 10) * p
yield base + ((d - 1) % 10) * p
p *= 10
def expand(w):
out = [[] for _ in range(T)]
for s in frontier[w]:
for n in neighbors(s):
out[n % T].append(n)
return out
def claim(w, outboxes):
seen, nxt = visited[w], []
for box in outboxes:
for n in box[w]:
if n not in seen:
seen.add(n)
nxt.append(n)
return nxt
level = 0
with ThreadPoolExecutor(T) as pool:
while any(frontier):
level += 1
outboxes = list(pool.map(expand, range(T)))
frontier = list(pool.map(lambda w: claim(w, outboxes), range(T)))
if goal in visited[goal % T]:
return level
return -1
Why it is correct.
- Each
pool.mapcall is a barrier, so level d+1 is built only from level d. - Each state is inserted by exactly one owner, so no state is expanded twice.
- The goal is checked right after the level that discovers it, so the returned level is its shortest distance.
Complexity is O(V + E) total work, roughly O((V + E) / T) wall time plus one barrier per level, and the number of levels is bounded by the graph diameter (at most 5n here).
Determinism
- The distance is always deterministic, since it depends on level structure, not scheduling.
- Frontier order and parent pointers are not deterministic with CAS, because the winner depends on timing. For a reproducible path, either resolve parents with an atomic-min on parent ID, or sort each next frontier at O(F log F) per level.
- Ownership partitioning with ordered inbox scanning, as above, is deterministic without extra work.
Trade-offs
| Concern | CAS on shared array | Ownership partitioning |
|---|---|---|
| Contention | Cache-line bouncing on hot words | None on visited, but barrier cost |
| Memory | One shared array | Array plus outbox buffers |
| Determinism | Needs extra work | Easy to get |
| Distributed extension | Hard | Natural |
Other points to name: bidirectional BFS can cut the explored space dramatically and is often a bigger win than adding threads; barrier cost matters when levels are narrow (early and late levels), so fall back to sequential processing for small frontiers.
Common mistakes
- Parallelizing the 4-wheel problem and ignoring overhead.
- Using one shared locked queue, which serializes the threads.
- Letting levels overlap, which breaks shortest-path correctness.
- Checking the visited flag and setting it as separate non-atomic steps, causing duplicate expansion.
- Forgetting to treat dead-end start or target, or start equal to target.
- Claiming the path is deterministic when only the distance is.
Validation
Compare against the sequential BFS on random dead-end sets, run under a thread sanitizer, and benchmark speedup versus thread count to find where barrier and memory-bandwidth limits flatten the curve.