← Google bank

Google · Question 70 · Graphs

Word Ladder

GraphsPythoncode⏱ O(MN26)💾 O(N)
Product-based

Problem

Find shortest transformation sequence length from beginWord to endWord changing one letter at a time.

Approach

Use BFS on the word graph where edges represent a single-letter difference.

Time O(MN26)Space O(N)

How it works

  1. 1BFS from beginWord.
  2. 2Generate all single-letter transformations.
  3. 3Enqueue valid words and remove them to avoid repeats.
  4. 4Return the length when endWord is found.

Sample input / output

Input:
hit cog
6
hot dot dog lot log cog
Output:
5

Constraints

1 <= beginWord.length <= 10; wordList.length up to 5000; all words same length and lowercase.

Solution — read it, then walk it

Time O(MN26)Space O(N)Loops 3Branches 4Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesno↻ repeat↻ repeatyes↻ repeat↻ repeatyesnoSTARTfrom collections importdequeDEFINEladderLength(beginWord,endWord, wordList)wordSet = set(wordList)if endWord not inwordSetRETURN 0queue = deque([(beginWord,1)])while queueword, length =queue.popleft()if word == endWordRETURN lengthfor i inrange(len(word))for c in'abcdefghijklmnopqrstuvwxyz'new_word = word[:i] + c +word[i + 1:]if new_word in wordSetwordSet.remove(new_word)queue.append((new_word,length + 1))RETURN 0DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)beginWord = next(it);endWord = next(it)n = int(next(it))wordList = [next(it) for _in range(n)]print(ladderLength(beginWord,endWord, wordList))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/28

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits