|
| 1 | +# Difficult problem: review later |
| 2 | +# https://leetcode.com/problems/longest-common-prefix-of-k-strings-after-removal |
| 3 | +# Trie |
| 4 | +# For each index, we consider removing it individually |
| 5 | +# There are only 2 possible answers, if we can't make it the max, make it the second max |
| 6 | + |
| 7 | +from collections import defaultdict, Counter |
| 8 | + |
| 9 | + |
| 10 | +class Trie: |
| 11 | + def __init__(self): |
| 12 | + self.count = 0 # number of times this word is stored |
| 13 | + self.prefix_count = 0 # number of words that can be reached from this node |
| 14 | + self.children = defaultdict(Trie) |
| 15 | + self.idx = [] # index of words stored in this node |
| 16 | + |
| 17 | + def insert(self, word: str, idx) -> None: |
| 18 | + cur = self |
| 19 | + cur.prefix_count += 1 |
| 20 | + for char in word: |
| 21 | + cur = cur.children[char] |
| 22 | + cur.prefix_count += 1 |
| 23 | + cur.count += 1 |
| 24 | + cur.idx.append(idx) |
| 25 | + |
| 26 | + def get_k_nodes(self, n, k): |
| 27 | + res = [-1] * n |
| 28 | + |
| 29 | + def dfs(cur, depth, ans): |
| 30 | + if cur.prefix_count >= k: # current point works as a prefix |
| 31 | + ans = depth |
| 32 | + for i in cur.idx: |
| 33 | + res[i] = ans |
| 34 | + for val in cur.children.values(): |
| 35 | + dfs(val, depth + 1, ans) |
| 36 | + |
| 37 | + dfs(self, 0, 0) |
| 38 | + return res |
| 39 | + |
| 40 | + |
| 41 | +def longestCommonPrefix(words: list[str], k: int) -> list[int]: |
| 42 | + n = len(words) |
| 43 | + if n == k: |
| 44 | + return [0] * n |
| 45 | + |
| 46 | + trie = Trie() |
| 47 | + for i in range(n): |
| 48 | + trie.insert(words[i], i) |
| 49 | + |
| 50 | + pre = trie.get_k_nodes(n, k) |
| 51 | + freq = Counter(pre) |
| 52 | + |
| 53 | + freq = sorted(freq.items(), reverse=True) + [(0, n + 1)] |
| 54 | + # print(freq) |
| 55 | + |
| 56 | + ans = [0] * n |
| 57 | + for i in range(n): |
| 58 | + # only `k` of first max, removing it makes it not enough |
| 59 | + # must take second max |
| 60 | + if pre[i] == freq[0][0] and freq[0][1] == k: |
| 61 | + ans[i] = freq[1][0] |
| 62 | + # otherwise take first max |
| 63 | + else: |
| 64 | + ans[i] = freq[0][0] |
| 65 | + return ans |
| 66 | + |
| 67 | + |
| 68 | +print(longestCommonPrefix(["ccd", "adc", "dba", "bff", "cbfae", "fcae", "cbbc"], 3)) |
| 69 | +print(longestCommonPrefix(words=["juaa", "run", "run", "juaa", "run"], k=2)) |
| 70 | +print(longestCommonPrefix(words=["dog", "racer", "car"], k=2)) |
0 commit comments