Approach
Sorting and greedy selection
For Design Search Autocomplete System, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 74 lines of Java from the credited upstream file 642.java.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class TrieNode implements Comparable<TrieNode> {2 public TrieNode[] children = new TrieNode[128];3 public String s = null;4 public int time = 0;5 public List<TrieNode> top3 = new ArrayList<>();6 7 public int compareTo(TrieNode o) {8 if (this.time == o.time)9 return this.s.compareTo(o.s);10 return o.time - this.time;11 }12 13 public void update(TrieNode node) {14 if (!this.top3.contains(node))15 this.top3.add(node);16 Collections.sort(top3);17 if (top3.size() > 3)18 top3.remove(top3.size() - 1);19 }20}21 22class AutocompleteSystem {23 public AutocompleteSystem(String[] sentences, int[] times) {24 for (int i = 0; i < sentences.length; ++i)25 insert(sentences[i], times[i]);26 }27 28 public List<String> input(char c) {29 if (c == '#') {30 insert(sb.toString(), 1);31 curr = root;32 sb = new StringBuilder();33 return new ArrayList<>();34 }35 36 sb.append(c);37 38 if (curr != null)39 curr = curr.children[c];40 if (curr == null)41 return new ArrayList<>();42 43 List<String> ans = new ArrayList<>();44 45 for (TrieNode node : curr.top3)46 ans.add(node.s);47 48 return ans;49 }50 51 private TrieNode root = new TrieNode();52 private TrieNode curr = root;53 private StringBuilder sb = new StringBuilder();54 55 private void insert(final String s, int time) {56 TrieNode node = root;57 for (final char c : s.toCharArray()) {58 if (node.children[c] == null)59 node.children[c] = new TrieNode();60 node = node.children[c];61 }62 node.s = s;63 node.time += time;64 65 66 TrieNode leaf = node;67 node = root;68 for (final char c : s.toCharArray()) {69 node = node.children[c];70 node.update(leaf);71 }72 }73}74