958. Every Shortest Ladder

A puzzle app turns one code word into another by changing exactly one letter at a time, and every code word you pass through (other than begin) must be listed in words. A shortest ladder never repeats a word.

Return every shortest ladder from begin to end, each as the list of words from begin first to end last. The order of the ladders in the returned list does not matter (any order is accepted), but the words inside one ladder must be in order. If end is not in words or cannot be reached, return an empty list. begin need not be in words.

Example 1

Input:
begin = "tore"end = "pile"words = ["tire","tile","pore","pole","pile","tote","tone"]
Output:
[["tore","pore","pole","pile"],["tore","tire","tile","pile"]]
Explanation:

Two ladders of length four exist: tore-tire-tile-pile and tore-pore-pole-pile.

Example 2

Input:
begin = "pen"end = "tip"words = ["pin","pip","ten","tin","pet","tip","pep"]
Output:
[["pen","pep","pip","tip"],["pen","pin","pip","tip"],["pen","pin","tin","tip"],["pen","ten","tin","tip"]]
Explanation:

Every letter differs, so three single-letter changes are needed, and several orders of those changes work.

Example 3

Input:
begin = "mask"end = "task"words = ["tack","mark","mast","mist"]
Output:
[]
Explanation:

The target task is not in words, so no ladder can end there.

Constraints

  • 1 ≤ begin.length ≤ 8; begin, end and all words are lowercase letters of the same length
  • begin ≠ end; 1 ≤ words.length ≤ 5000; the words are distinct
  • The number of shortest ladders is at most 500

How this problem is judged

Answers
The outer list may be in any order. Everything inside each item must match exactly.
Time per case
Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms

Expected complexity

Time
O(n * L^2 + output size)
Space
O(n * L)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…