All problems
0055HardHash TableStringBreadth-First SearchBidirectional Search

Dial Code Rewrite

Tracked in this browser only
Write code

Trains the technique from

LeetCode 127Word Ladder

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A stockroom cabinet is held shut by a row of letter dials that currently spell startCode. You want the dials to spell targetCode instead.

Spinning a single dial rewrites exactly one position of the current code, and the cabinet's firmware refuses to settle on anything it does not recognise: after every single spin, the code showing on the dials must be one of the strings in approved. startCode is where you begin so it does not have to be listed, but targetCode does, since the dials have to settle on it.

Count the codes along the shortest run of spins that gets from startCode to targetCode, including startCode and targetCode themselves. Two codes in a row along that run differ at exactly one position. When the dials cannot reach targetCode at all, report 0.

Examples

Example 1

Input
startCode = "cold", targetCode = "warm", approved = ["cord", "card", "ward", "warm", "word", "wart"]
Output
5

The dials can go cold, cord, card, ward, warm, which is five codes. Nothing shorter works, because cold and warm disagree at all four positions and so at least four spins are needed.

Example 2

Input
startCode = "cold", targetCode = "warm", approved = ["cord", "card", "ward", "word", "wart"]
Output
0

The target itself is absent from the approved strings, so the firmware would never let the dials rest on it.

Example 3

Input
startCode = "damp", targetCode = "lamp", approved = ["lamp", "dame", "lame"]
Output
2

One spin of the leading dial reaches an approved target, so the run holds just the two codes.

Constraints

  • 1 <= startCode.length <= 10
  • targetCode.length == startCode.length
  • 1 <= approved.length <= 5000
  • approved[i].length == startCode.length
  • startCode, targetCode and approved[i] consist of lowercase English letters
  • startCode != targetCode
  • All strings in approved are distinct

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def shortest_rewrite(startCode: str, targetCode: str, approved: list[str]) -> int:
Java
public int shortestRewrite(String startCode, String targetCode, List<String> approved)
September 7
Apply