Skip to content

Commit e0df92c

Browse files
authored
Create Word_Ladder.py
1 parent fb6e547 commit e0df92c

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution:
2+
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
3+
'''
4+
Make a directed graph connecting words with 1 character difference. Then do BFS until you reach endWord, or all nodes are traversed. Return 0 if you never reached endWord, otherwise return the level count.
5+
O(N^2 * K) Time.
6+
K = length of words. N = number of words.
7+
Building adjacency list is O(N * K^2), because for each word we loop through each character and then perform splicing to create our pattern. Splicing and Inner loop are both O(K).
8+
Doing BFS on the graph is O(N^2 * K). BFS on fully connected graph = O(V+E) = O(V^2). We also generate patterns in O(K) time on each recursive call.
9+
N >> K so the BFS TC takes precendence.
10+
O(N * K^2) Space. Each word has length K. Each word is stored K times (for each possible pattern) in adjacency list. There are N words.
11+
Python: Create a Set/Queue with initial values by passing in a list, e.g. deque([beginWord])
12+
'''
13+
adj = defaultdict(list)
14+
wordList.append(beginWord)
15+
for word in wordList:
16+
for i in range(len(word)):
17+
pattern = word[:i] + "*" + word[i+1:]
18+
adj[pattern].append(word)
19+
20+
q = deque([beginWord])
21+
visited = set([beginWord])
22+
seqLen = 1
23+
while q:
24+
for i in range(len(q)):
25+
word = q.popleft()
26+
for j in range(len(word)):
27+
pattern = word[:j] + "*" + word[j+1:]
28+
for neighbor in adj[pattern]:
29+
if neighbor not in visited:
30+
q.append(neighbor)
31+
visited.add(neighbor)
32+
if neighbor == endWord:
33+
return seqLen + 1
34+
seqLen += 1
35+
return 0

0 commit comments

Comments
 (0)