- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 103 lines of Python from the credited upstream file prefix-and-suffix-search.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234 5import collections6 7 8class WordFilter(object):9 10 def __init__(self, words):11 """12 :type words: List[str]13 """14 _trie = lambda: collections.defaultdict(_trie)15 self.__trie = _trie()16 17 for weight, word in enumerate(words):18 word += '#'19 for i in xrange(len(word)):20 cur = self.__trie21 cur["_weight"] = weight22 for j in xrange(i, 2*len(word)-1):23 cur = cur[word[j%len(word)]]24 cur["_weight"] = weight25 26 def f(self, prefix, suffix):27 """28 :type prefix: str29 :type suffix: str30 :rtype: int31 """32 cur = self.__trie33 for letter in suffix + '#' + prefix:34 if letter not in cur:35 return -136 cur = cur[letter]37 return cur["_weight"]38 39 4041424344class Trie(object):45 46 def __init__(self):47 _trie = lambda: collections.defaultdict(_trie)48 self.__trie = _trie()49 50 def insert(self, word, i):51 def add_word(cur, i):52 if "_words" not in cur:53 cur["_words"] = []54 cur["_words"].append(i)55 56 cur = self.__trie57 add_word(cur, i)58 for c in word:59 cur = cur[c]60 add_word(cur, i)61 62 def find(self, word):63 cur = self.__trie64 for c in word:65 if c not in cur:66 return []67 cur = cur[c]68 return cur["_words"]69 70 71class WordFilter2(object):72 73 def __init__(self, words):74 """75 :type words: List[str]76 """77 self.__prefix_trie = Trie()78 self.__suffix_trie = Trie()79 for i in reversed(xrange(len(words))):80 self.__prefix_trie.insert(words[i], i)81 self.__suffix_trie.insert(words[i][::-1], i)82 83 def f(self, prefix, suffix):84 """85 :type prefix: str86 :type suffix: str87 :rtype: int88 """89 prefix_match = self.__prefix_trie.find(prefix)90 suffix_match = self.__suffix_trie.find(suffix[::-1])91 i, j = 0, 092 while i != len(prefix_match) and j != len(suffix_match):93 if prefix_match[i] == suffix_match[j]:94 return prefix_match[i]95 elif prefix_match[i] > suffix_match[j]:96 i += 197 else:98 j += 199 return -1100 101 102 103