Marquee Letter Swaps

Hardbreadth-first searchAlso known as Word Ladder

An old cinema has a sign above the door made of loose letter tiles. As a running joke with the neighborhood, the manager changes it a little every night: she climbs the ladder once and swaps exactly one tile. The rule regulars love is that the sign must always show a real word from the house list of approved words.

Tonight it says cold, and for the winter festival she wants it to say warm. Each night is one tile swap, so the path might run cold → cord → word → ward → warm. How few nights can it take?

Your task

Write nightsToChange(current, target, approved). Each night you change exactly one letter of the sign, and the new word must be in approved. Return the fewest nights needed to go from current to target, or -1 if it cannot be done.

current does not have to be in approved (it is already on the sign), but target and every word in between do. If current equals target, return 0. All words have the same length and use lowercase letters a to z.

nightsToChange(current: string, target: string, approved: string[]) → int

Examples

Example 1
Input
current = "cold"
target = "warm"
approved = ["cord", "card", "word", "ward", "warm", "worm", "core"]
Output
4
Why

One shortest path is cold → cord → word → worm → warm. Each step changes one letter and lands on an approved word. Every letter of cold differs from warm, so at least 4 nights are needed, and 4 is enough.

Example 2
Input
current = "hat"
target = "hot"
approved = ["hit", "hut"]
Output
-1
Why

hat and hot differ by one letter, but hot is not on the approved list, so the sign can never show it. Return -1.

Example 3
Input
current = "ab"
target = "ba"
approved = ["aa", "bb", "ba"]
Output
2
Why

ab → aa → ba or ab → bb → ba. Two nights.

Constraints

  • 1 ≤ word length ≤ 8
  • 0 ≤ approved.length ≤ 2,000
  • current, target and every approved word have the same length
  • approved has no duplicates
Start with brute force

Build the full graph first by comparing every pair of approved words letter by letter, then run breadth-first search. With 2,000 words that is about 2 million pairs, each compared up to 8 letters. It works, but building the graph is the slow part.

The worse idea is to change letters greedily toward the target, only touching positions that are still wrong. Sometimes the only path moves a correct letter away and back. Going from aa to bb with only ac, bc and bb approved, neither ba nor ab is allowed, so you must go aa → ac → bc → bb. Greedy gives up there even though a real path exists.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code