Marquee Letter Swaps

Hardbreadth-first searchAlso known as Word Ladder

An old cinema's sign is made of loose letter tiles. Every night the manager climbs the ladder and swaps exactly one tile, and the sign must always show a word from the house list of approved words.

Tonight the sign says cold, and for the winter festival she wants it to say warm. One possible path is cold → cord → word → ward → warm, and she wants to know the fewest nights it can take.

Your task

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

current need not be in approved (it is already on the sign), but target and every word in between must be. If current equals target, return 0. All words have the same length and use lowercase 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. 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 approved, 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 by comparing every pair of approved words, then run breadth-first search. 2,000 words make about 2 million pairs of up to 8 letters each. This works, but building the graph is slow.

A worse approach is to change letters greedily toward the target. Sometimes the only path moves a correct letter away and back. For example, from aa to bb with only ac, bc and bb approved, you must go aa → ac → bc → bb, so a greedy search gives up even though a 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