- 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
- 54 lines of Python from the credited upstream file 3485.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.
1class TrieNode:2 def __init__(self):3 self.children: dict[str, TrieNode] = {}4 self.count = 05 6 7class Trie:8 def __init__(self, k: int):9 self.k = k10 self.root = TrieNode()11 self.prefixLengthsCount = collections.Counter()12 self.prefixLengths = SortedList()13 14 def insert(self, word: str) -> None:15 node = self.root16 for i, c in enumerate(word):17 sz = i + 118 node = node.children.setdefault(c, TrieNode())19 node.count += 120 if node.count >= self.k:21 self.prefixLengthsCount[sz] += 122 if self.prefixLengthsCount[sz] == 1:23 self.prefixLengths.add(-sz)24 25 def erase(self, word: str) -> None:26 node = self.root27 for i, c in enumerate(word):28 sz = i + 129 node = node.children[c]30 if node.count == self.k:31 self.prefixLengthsCount[sz] -= 132 if self.prefixLengthsCount[sz] == 0:33 self.prefixLengths.remove(-sz)34 node.count -= 135 36 def getLongestCommonPrefix(self) -> int:37 return 0 if not self.prefixLengths else -self.prefixLengths[0]38 39 40class Solution:41 def longestCommonPrefix(self, words: list[str], k: int) -> list[int]:42 ans = []43 trie = Trie(k)44 45 for word in words:46 trie.insert(word)47 48 for word in words:49 trie.erase(word)50 ans.append(trie.getLongestCommonPrefix())51 trie.insert(word)52 53 return ans54