KatInterview

Multithreaded Shortest-Path Search for a Wheel Combination Lock

System DesignModel answer
HardModel answerSystem Designbfsconcurrencyparallel-algorithms

Last 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:

  1. Whether parallelism is even worthwhile, and at what problem size.
  2. How to split the search work among threads, and how to keep BFS level ordering correct.
  3. How to build a thread-safe visited set and the queues or frontiers, so that no state is explored twice.
  4. The edge cases: start or target is a dead end, start equals target, unreachable target.
  5. 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.