HardNo. 0127

Word Ladder — LeetCode 127 Python Solution

Topics
Breadth-First Search, Hash Table, String
Reading time
4 min

The problem

A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter.

Example

Input
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output
5
Explanation
One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.

Python solution

PythonSolution
while q1 and q2:
    if len(q1) <= len(q2):
        # Prioritize the queue with fewer elements for expansion
        extend(m1, m2, q1)
    else:
        extend(m2, m1, q2)


def extend(m1, m2, q):
    # New round of expansion
    for _ in range(len(q)):
        p = q.popleft()
        step = m1[p]
        for t in next(p):
            if t in m1:
                # Already visited before
                continue
            if t in m2:
                # The other direction has been searched, indicating that a shortest path has been found
                return step + 1 + m2[t]
            q.append(t)
            m1[t] = step + 1

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Breadth-First Search

Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 127. Word Ladder is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.

The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0126Word Ladder IIHard
0433Minimum Genetic MutationMedium
0721Accounts MergeMedium
0752Open the LockMedium
0839Similar String GroupsHard
0854K-Similar StringsHard

Frequently asked questions

How hard is LeetCode 127. Word Ladder?

LeetCode 127. Word Ladder is rated Hard on LeetCode.

What is the time complexity of LeetCode 127. Word Ladder?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 127. Word Ladder?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 127. Word Ladder cover?

LeetCode 127. Word Ladder is tagged Breadth-First Search, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.