Google · Question 70 · Graphs
Word Ladder
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
- 1BFS from beginWord.
- 2Generate all single-letter transformations.
- 3Enqueue valid words and remove them to avoid repeats.
- 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.
- 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