DEV Community

Nora Vale
Nora Vale

Posted on

Validating Word Ladder Routes Without a Backend

A word ladder puzzle looks trivial to build until the first user submits a route that is almost legal. Every rung has to be a real word, every step has to change exactly one letter, and the whole sequence has to end on the target. Doing that validation client-side is simple, fast, and removes an entire category of backend work.

The core data structure is an adjacency map. Build it once from the word list, then every check is a lookup instead of a scan.

// words: array of four-letter lowercase strings
const neighbours = new Map();
for (const w of words) {
  const set = new Set();
  for (let i = 0; i < w.length; i++) {
    for (let c = 97; c <= 122; c++) {
      const candidate = w.slice(0, i) + String.fromCharCode(c) + w.slice(i + 1);
      if (candidate !== w && wordSet.has(candidate)) set.add(candidate);
    }
  }
  neighbours.set(w, set);
}
Enter fullscreen mode Exit fullscreen mode

With that map, validating a submitted route is four lines: check each word exists, check each step is one edit away, check the first and last words. The expensive part is building the map, and it is small enough to ship as a static JSON file.

Two things matter for sizing. A four-letter English list is about 3,000 to 6,000 common words, which produces a JSON adjacency map of a few hundred kilobytes. Gzipped that is well under 100 kB, which is smaller than most hero images. Build it at deploy time, cache it, and never compute it in the browser on every visit.

The subtle part is that the adjacency map is also the solver. Breadth-first search from the start word gives the shortest route, and the same search can cap the number of hints a user is allowed to reveal. There is no separate logic for hints and solutions, which is why the whole thing fits in a static site.

If you want to see the result of this approach in production, the puzzle at the daily ladder is built exactly this way, and visit the site to look at how the answer archive is generated from the same graph. No server, no database, no rate limits to manage.

Top comments (0)