- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 54 lines of Python from the credited upstream file 269.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def alienOrder(self, words: list[str]) -> str:3 graph = {}4 inDegrees = [0] * 265 6 self._buildGraph(graph, words, inDegrees)7 return self._topology(graph, inDegrees)8 9 def _buildGraph(10 self,11 graph: dict[str, set[str]],12 words: list[str],13 inDegrees: list[int],14 ) -> None:15 16 for word in words:17 for c in word:18 if c not in graph:19 graph[c] = set()20 21 for first, second in zip(words, words[1:]):22 length = min(len(first), len(second))23 for j in range(length):24 u = first[j]25 v = second[j]26 if u != v:27 if v not in graph[u]:28 graph[u].add(v)29 inDegrees[ord(v) - ord('a')] += 130 break 31 32 if j == length - 1 and len(first) > len(second):33 graph.clear()34 return35 36 def _topology(self, graph: dict[str, set[str]], inDegrees: list[int]) -> str:37 s = ''38 q = collections.deque()39 40 for c in graph:41 if inDegrees[ord(c) - ord('a')] == 0:42 q.append(c)43 44 while q:45 u = q.pop()46 s += u47 for v in graph[u]:48 inDegrees[ord(v) - ord('a')] -= 149 if inDegrees[ord(v) - ord('a')] == 0:50 q.append(v)51 52 53 return s if len(s) == len(graph) else ''54