Find word sequence with 1–2 char changes
Company: Reddit
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates graph traversal and shortest-path search skills, specifically reasoning about BFS vs DFS, string transformation modeling, and algorithmic time/space complexity within the Coding & Algorithms domain.
Constraints
- 0 <= len(wordList) <= 5000
- 1 <= len(beginWord) == len(endWord) <= 10
- All words in wordList are unique, lowercase, and the same length as beginWord
Examples
Input: ("hit", "cog", ["hot", "dot", "dog", "lot", "log"])
Expected Output: ["hit", "hot", "cog"]
Explanation: 'hot' differs by 1 from 'hit', and 'cog' differs by 2 from 'hot'. No 1-step path exists because 'hit' and 'cog' differ in 3 positions.
Input: ("aaaa", "bbbb", ["aabb"])
Expected Output: ["aaaa", "aabb", "bbbb"]
Explanation: 'aaaa' -> 'aabb' changes the last two positions, then 'aabb' -> 'bbbb' changes the first two.
Input: ("same", "same", ["came", "lame"])
Expected Output: ["same"]
Explanation: The start already equals the target, so the shortest sequence contains only that word.
Input: ("aaa", "bbb", ["aac", "acc", "ccc"])
Expected Output: []
Explanation: You can reach some dictionary words, but none lead to 'bbb' by a sequence of 1- or 2-character substitutions.
Input: ("abc", "abd", [])
Expected Output: ["abc", "abd"]
Explanation: 'abd' is one substitution away from 'abc', and the final word is allowed to be outside the dictionary.
Hints
- Model each word as a node in an unweighted graph. If you need the shortest path, BFS is usually the right traversal.
- Avoid comparing every pair of words. Instead, group words by patterns created by replacing 1 or 2 positions with a wildcard so neighbors can be found quickly.