Approach
Breadth-first search
For Stream of Characters2, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 83 lines of Python from the credited upstream file stream-of-characters2.py.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12345678 910111213 14import collections15 16 17class AhoNode(object):18 def __init__(self):19 self.children = collections.defaultdict(AhoNode)20 self.suffix = None21 self.outputs = []22 23 24class AhoTrie(object):25 26 def step(self, letter):27 while self.__node and letter not in self.__node.children:28 self.__node = self.__node.suffix29 self.__node = self.__node.children[letter] if self.__node else self.__root30 return self.__node.outputs 31 32 def __init__(self, patterns):33 self.__root = self.__create_ac_trie(patterns)34 self.__node = self.__create_ac_suffix_and_output_links(self.__root)35 36 def __create_ac_trie(self, patterns): 37 root = AhoNode()38 for i, pattern in enumerate(patterns):39 node = root40 for c in pattern:41 node = node.children[c]42 node.outputs.append(i)43 return root44 45 def __create_ac_suffix_and_output_links(self, root): 46 queue = collections.deque()47 for node in root.children.itervalues():48 queue.append(node)49 node.suffix = root50 51 while queue:52 node = queue.popleft()53 for c, child in node.children.iteritems():54 queue.append(child)55 suffix = node.suffix56 while suffix and c not in suffix.children:57 suffix = suffix.suffix58 child.suffix = suffix.children[c] if suffix else root59 child.outputs += child.suffix.outputs 60 61 return root62 63 64class StreamChecker(object):65 66 def __init__(self, words):67 """68 :type words: List[str]69 """70 self.__trie = AhoTrie(words)71 72 def query(self, letter): 73 """74 :type letter: str75 :rtype: bool76 """77 return len(self.__trie.step(letter)) > 078 79 80818283