I’m solving this LeetCode problem and here’s my code:
JavaScript
x
34
34
1
class Solution:
2
def alienOrder(self, words: List[str]) -> str:
3
adjacent = defaultdict(set)
4
5
for i in range(1, len(words)):
6
w1, w2 = words[i - 1], words[i]
7
min_len = min(len(w1), len(w2))
8
if len(w1) > len(w2) and w1[:min_len] == w2[:min_len]:
9
return ""
10
for j in range(min_len):
11
if w1[j] != w2[j]:
12
adjacent[w1[j]].add(w2[j]) # modify, not in the loop causing error
13
break
14
15
visited = dict()
16
res = []
17
18
def dfs(c):
19
if c in visited:
20
return visited[c]
21
22
visited[c] = True
23
for neighbor in adjacent[c]: # read only
24
if dfs(neighbor):
25
return True
26
visited[c] = False
27
res.append(c)
28
return False
29
30
for c in adjacent: # RuntimeError: dictionary changed size during iteration
31
if dfs(c):
32
return ''
33
return ''.join(reversed(res))
34
The line for c in adjacent
throws “RuntimeError: dictionary changed size during iteration”, which I don’t understand. I’m not modifying adjacent
in dfs()
, am I?
Advertisement
Answer
The main Problem is when dfs method is called it uses this line
JavaScript
1
2
1
for neighbor in adjacent[c]:
2
This just returns the associated value if it exists in defaultdict, if it doesn’t exist in it, it creates and adds a key if you try to access key that doesn’t exist.
Potential line that triggers accessing adjacent defaultdict without knowing whether it exist or not is
JavaScript
1
2
1
if dfs(neighbor):
2
neighbor might be or might not be in adjacent defaultdict this causes defaultdict to change. You might check if it exists if not u might want to skip.