- 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
- 66 lines of Java from the credited upstream file 3485.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 4 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 public TrieNode[] children = new TrieNode[26];3 public int count = 0;4}5 6class Trie {7 public Trie(int k) {8 this.k = k;9 }10 11 public void insert(final String word) {12 TrieNode node = root;13 for (int i = 0; i < word.length(); ++i) {14 final int sz = i + 1;15 final int index = word.charAt(i) - 'a';16 if (node.children[index] == null)17 node.children[index] = new TrieNode();18 node = node.children[index];19 ++node.count;20 if (node.count >= k && prefixLengthsCount.merge(sz, 1, Integer::sum) == 1)21 prefixLengths.add(sz);22 }23 }24 25 public void erase(final String word) {26 TrieNode node = root;27 for (int i = 0; i < word.length(); ++i) {28 final int sz = i + 1;29 final int index = word.charAt(i) - 'a';30 if (node.children[index] == null)31 node.children[index] = new TrieNode();32 node = node.children[index];33 if (node.count == k && prefixLengthsCount.merge(sz, -1, Integer::sum) == 0)34 prefixLengths.remove(sz);35 --node.count;36 }37 }38 39 public int getLongestCommonPrefix() {40 return prefixLengths.isEmpty() ? 0 : prefixLengths.first();41 }42 43 private final int k;44 private TrieNode root = new TrieNode();45 private Map<Integer, Integer> prefixLengthsCount = new HashMap<>();46 private TreeSet<Integer> prefixLengths = new TreeSet<>(Collections.reverseOrder());47}48 49class Solution {50 public int[] longestCommonPrefix(String[] words, int k) {51 final int[] ans = new int[words.length];52 Trie trie = new Trie(k);53 54 for (final String word : words)55 trie.insert(word);56 57 for (int i = 0; i < words.length; ++i) {58 trie.erase(words[i]);59 ans[i] = trie.getLongestCommonPrefix();60 trie.insert(words[i]);61 }62 63 return ans;64 }65}66