Counts map + filter and sort
Time O(S log S) per input for S sentences Space O(total characters)On each character, scan all sentences that start with the prefix, sort by (−count, text), take 3. On '#', increment the count of the prefix and reset.
import java.util.*;
class AutocompleteSystem {
private final Map<String, Integer> counts = new HashMap<>();
private final StringBuilder prefix = new StringBuilder();
public AutocompleteSystem(String[] sentences, int[] times) {
for (int i = 0; i < sentences.length; i++) counts.merge(sentences[i], times[i], Integer::sum);
}
public List<String> input(char c) {
if (c == '#') {
counts.merge(prefix.toString(), 1, Integer::sum);
prefix.setLength(0);
return new ArrayList<>();
}
prefix.append(c);
String p = prefix.toString();
List<String> matches = new ArrayList<>();
for (String s : counts.keySet()) if (s.startsWith(p)) matches.add(s);
matches.sort((a, b) -> !counts.get(a).equals(counts.get(b)) ? counts.get(b) - counts.get(a) : a.compareTo(b));
return new ArrayList<>(matches.subList(0, Math.min(3, matches.size())));
}
}Verdict: Simple and fast enough for these limits.