15% off all plans & roadmaps Use code
See plansDesign Search Autocomplete System
- LeetCode 642
- Hard
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: Design a class that records typed sentences and returns the top 3 completions for each prefix. Store sentences in a trie where every node keeps its best 3 sentences, so each keystroke costs only the prefix length.
Problem
You are given a list of historical sentences sentences and an integer array times, where sentences[i] is a sentence already typed and times[i] is how many times it was typed. Implement the AutocompleteSystem class.
AutocompleteSystem(String[] sentences, int[] times)starts the system with these sentences and frequencies.List<String> input(char c)runs each time the user types a characterc.- If
cis not'#', appendcto the current prefix and return the top 3 historical sentences that start with that prefix. Sort them by highest frequency first. Break ties by lexicographically smaller sentence first. - If
cis'#', the current prefix is a finished sentence. Add it to the history, or increase its frequency if it already exists. Reset the prefix to empty and return an empty list.
- If
The system must handle up to 5000 calls to input efficiently.
Example 1
Input: sentences = [], times = [], inputs = ["a", "b", "c", "#"] Output: [[], [], [], []]
Constraints
n == sentences.length == times.length1 <= n <= 1001 <= sentences[i].length <= 1001 <= times[i] <= 50- Each sentence consists of lowercase letters and spaces.
- The input character
cis a lowercase letter, a space' ', or'#'. - The total number of characters input via
inputwill not exceed 200.
Return the list of top 3 matching sentences for each call to input. When c is '#', return an empty list.
Constraints that matter
- Up to 200 characters are typed in total, so each keystroke can cost time proportional to the prefix length. Work that grows with the number of sentences on every call is the part to avoid.
- Each sentence has at most 100 characters and there are at most 100 of them, so a single update that walks one sentence's path is cheap.
- Frequencies stay small (at most 50 per sentence plus at most 200 additions), so plain integers are safe for counts.
- Only the top 3 results are returned, so each node only needs to remember 3 sentences.
Hints
Hint 1
The problem asks for ranked prefix lookups, and the history changes after each finished sentence.
Hint 2
Keep a dictionary that maps each sentence to its count, plus the current prefix as a string.
Solution
Intuition
The problem asks for ranked prefix lookups, and the history changes after each finished sentence. A brute force scan has to check every stored sentence on every keystroke. A trie groups sentences by their shared prefixes, so the sentences you need for a prefix are all below one node.
It is like a filing cabinet where each drawer is one prefix and holds a sticky note listing the three best sentences. Looking up a prefix opens one drawer and reads its note without checking anything else.
The second part of the pattern is precomputed answers. Each trie node can store the best 3 sentences in its subtree, so a lookup never walks the subtree. The cost moves to the update, which only happens when the user finishes a sentence.
This works because counts only go up. When one sentence's count rises, the only candidate that can enter a node's top 3 is that sentence itself. The other stored sentences keep their relative order.
Worked example
Input: sentences = [], times = [], inputs = ["a", "b", "c", "#"] Output: [[], [], [], []] Explanation: The system starts with no history, so the first three letters match nothing and return empty lists. The '#' saves the typed prefix "abc" with frequency 1 and returns an empty list, as required.
Approach 1: Brute force over a dictionary
Keep a dictionary that maps each sentence to its count, plus the current prefix as a string. On each letter, scan every key, keep the ones that start with the prefix, sort them by count and then by text, and return the first 3.
What's slow: every letter scans all stored sentences, even the ones that cannot match. The sort also runs over every match, when only 3 are needed. The work per letter depends on the number of sentences, not on the prefix length.
The insight that fixes it comes in the next approach. A trie puts all sentences with the same prefix under one node, and caching the answer at that node removes the scan entirely.
Steps
- Store each sentence in a dictionary and add its times to the count.
- Set the current prefix to the empty string.
- On a letter, append it to the prefix and scan every key in the dictionary.
- Keep the keys that start with the prefix.
- Sort the kept keys by count descending, then by text ascending.
- Return the first 3 keys.
- On '#', add 1 to the count of the prefix, clear the prefix, and return an empty list.
Dry run
The example starts with no sentences, so the dictionary is empty.
- Call 1, letter
a: the prefix becomesa. The scan finds no keys, so the result is[]. - Call 2, letter
b: the prefix becomesab. The scan finds no keys, so the result is[]. - Call 3, letter
c: the prefix becomesabc. The scan finds no keys, so the result is[]. - Call 4,
#: the dictionary gets the keyabcwith count 1. The prefix resets to empty and the result is[].
The output is [[], [], [], []], which matches the example.
Complexity
| Time | O(N * L + M log M) per letter, where N is the number of distinct sentences, L is the longest sentence, and M is the number of matches |
|---|---|
| Space | O(T), where T is the total number of characters in all distinct sentences |
Each letter checks every one of the N stored keys with a prefix test, and each test reads up to L characters, which gives O(N * L). The sort then orders the M matches, which takes O(M log M) comparisons. A '#' call hashes the prefix once, which is O(L). The dictionary holds all T characters of text.
PythonTested in our runner
from typing import List, Optional
class AutocompleteSystem:
def __init__(self, sentences: List[str], times: List[int]):
self.counts = {}
for s, t in zip(sentences, times):
self.counts[s] = self.counts.get(s, 0) + t
self.prefix = ""
def input(self, c: str) -> List[str]:
if c == '#':
self.counts[self.prefix] = self.counts.get(self.prefix, 0) + 1
self.prefix = ""
return []
self.prefix += c
matches = [s for s in self.counts if s.startswith(self.prefix)]
matches.sort(key=lambda s: (-self.counts[s], s))
return matches[:3]
JavaTested in our runner
import java.util.*;
class AutocompleteSystem {
private Map<String, Integer> counts = new HashMap<>();
private 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 String[] input(String c) {
if (c.equals("#")) {
counts.merge(prefix.toString(), 1, Integer::sum);
prefix.setLength(0);
return new String[0];
}
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) -> {
int ca = counts.get(a), cb = counts.get(b);
if (ca != cb) return cb - ca;
return a.compareTo(b);
});
String[] top = new String[Math.min(3, matches.size())];
for (int i = 0; i < top.length; i++) top[i] = matches.get(i);
return top;
}
}
C++Tested in our runner
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class AutocompleteSystem {
unordered_map<string, int> counts;
string prefix;
public:
AutocompleteSystem(vector<string>& sentences, vector<int>& times) {
for (size_t i = 0; i < sentences.size(); ++i) counts[sentences[i]] += times[i];
}
vector<string> input(string c) {
if (c == "#") {
counts[prefix] += 1;
prefix.clear();
return {};
}
prefix += c;
vector<string> matches;
for (auto& kv : counts) {
if (kv.first.compare(0, prefix.size(), prefix) == 0) matches.push_back(kv.first);
}
sort(matches.begin(), matches.end(), [&](const string& a, const string& b) {
if (counts[a] != counts[b]) return counts[a] > counts[b];
return a < b;
});
if (matches.size() > 3) matches.resize(3);
return matches;
}
};
JavaScriptTested in our runner
var AutocompleteSystem = function(sentences, times) {
this.counts = new Map();
this.prefix = "";
for (let i = 0; i < sentences.length; i++) {
this.counts.set(sentences[i], (this.counts.get(sentences[i]) || 0) + times[i]);
}
};
/**
* @param {string} c
* @return {string[]}
*/
AutocompleteSystem.prototype.input = function(c) {
if (c === '#') {
this.counts.set(this.prefix, (this.counts.get(this.prefix) || 0) + 1);
this.prefix = "";
return [];
}
this.prefix += c;
const matches = [];
for (const s of this.counts.keys()) {
if (s.startsWith(this.prefix)) matches.push(s);
}
matches.sort((a, b) => {
const ca = this.counts.get(a), cb = this.counts.get(b);
if (ca !== cb) return cb - ca;
return a < b ? -1 : (a > b ? 1 : 0);
});
return matches.slice(0, 3);
};
GoTested in our runner
import ("sort"; "strings")
type AutocompleteSystem struct {
counts map[string]int
prefix string
}
func Constructor(sentences []string, times []int) AutocompleteSystem {
sys := AutocompleteSystem{counts: map[string]int{}}
for i, s := range sentences {
sys.counts[s] += times[i]
}
return sys
}
func (this *AutocompleteSystem) input(c string) []string {
if c == "#" {
this.counts[this.prefix]++
this.prefix = ""
return []string{}
}
this.prefix += c
matches := []string{}
for s := range this.counts {
if strings.HasPrefix(s, this.prefix) {
matches = append(matches, s)
}
}
sort.Slice(matches, func(i, j int) bool {
a, b := matches[i], matches[j]
if this.counts[a] != this.counts[b] {
return this.counts[a] > this.counts[b]
}
return a < b
})
if len(matches) > 3 {
matches = matches[:3]
}
return matches
}
C#Tested in our runner
public class AutocompleteSystem {
private Dictionary<string, int> counts = new Dictionary<string, int>();
private string prefix = "";
public AutocompleteSystem(string[] sentences, int[] times) {
for (int i = 0; i < sentences.Length; i++) Bump(sentences[i], times[i]);
}
private void Bump(string s, int k) {
counts.TryGetValue(s, out int v);
counts[s] = v + k;
}
public string[] input(string c) {
if (c == "#") {
Bump(prefix, 1);
prefix = "";
return new string[0];
}
prefix += c;
var matches = new List<string>();
foreach (var s in counts.Keys) {
if (s.StartsWith(prefix, StringComparison.Ordinal)) matches.Add(s);
}
matches.Sort((a, b) => {
int ca = counts[a], cb = counts[b];
if (ca != cb) return cb.CompareTo(ca);
return string.CompareOrdinal(a, b);
});
int take = Math.Min(3, matches.Count);
return matches.GetRange(0, take).ToArray();
}
}
The Design (General/Specific) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Design (General/Specific)
Part of Design Patterns
Approach 2: Trie with top 3 cached per nodeOptimalDesign (General/Specific)
What's slow: the brute force scans every stored sentence on every letter, even though sentences that share a prefix are stored far apart in the dictionary.
The insight that fixes it: store the sentences in a trie, where each node is one prefix. All sentences that start with a prefix live under that prefix's node. A lookup walks the prefix once, which costs O(p), and then reads the answer from the node.
Each node keeps its best 3 sentences by count and then text. When a sentence is finished, only the nodes on its path can change. At each of those nodes, the sentence can only enter the top 3 from its own new count, because counts only go up. The node takes the old top 3 plus this sentence, sorts those at most 4 items, and keeps 3.
Why it is correct. Each node always holds the true top 3 sentences from its subtree, both at the start and after every update. Counts only go up, so a sentence outside a node's top 3 can enter only through its own increase, which the refresh checks. Every other sentence keeps its relative order, so re-sorting the old top 3 with the changed sentence loses no answer.
Steps
- Create a root node with an empty child map and an empty top list.
- For each initial sentence, add its times to a count map and refresh that sentence along its path.
- To refresh, visit the root and then every node for each character. At each node, combine its top list with the sentence, remove duplicates, sort, and keep 3.
- On a letter, append it to the prefix and follow the child for that letter. If a child is missing, return an empty list.
- At the node you reach, return a copy of its top list.
- On '#', add 1 to the count of the prefix, refresh the prefix along its path, clear the prefix, and return an empty list.
Dry run
The example starts with an empty trie, so every node top list is empty.
| Step | Input | Prefix after step | Walk result | Top lists after step | Returned |
|---|---|---|---|---|---|
| 0 | init, no sentences | (empty) | root only | root: [] | n/a |
| 1 | a | a | no child 'a' under root, walk stops | root: [] | [] |
| 2 | b | ab | no child 'a' under root, walk stops | root: [] | [] |
| 3 | c | abc | no child 'a' under root, walk stops | root: [] | [] |
| 4 | # | (empty) | creates nodes a, ab, abc; counts abc = 1; refresh path | root, a, ab, abc: ["abc"] | [] |
The final output is [[], [], [], []]. Step 4 is the only one that changes state. The new path gets abc in each node's top list, which a later lookup on a, ab, or abc would return.
Complexity
| Time | O(p) per letter, where p is the prefix length; O(L^2) per '#' or sentence refresh, where L is the sentence length |
|---|---|
| Space | O(T), where T is the total number of characters in all distinct sentences |
A letter walks at most p trie edges and copies at most 3 sentences, so it costs O(p). Refreshing a sentence of length L touches L + 1 nodes. Each touch sorts at most 4 strings whose comparisons cost up to L characters each, which gives O(L^2) per '#'. The trie has one node per distinct prefix, so it holds at most T nodes, and each node stores at most 3 sentence references.
PythonTested in our runner
from typing import List, Optional
class TrieNode:
def __init__(self):
self.children = {}
self.top = [] # up to 3 sentences, best first
class AutocompleteSystem:
def __init__(self, sentences: List[str], times: List[int]):
self.root = TrieNode()
self.counts = {}
self.prefix = ""
for s, t in zip(sentences, times):
self.counts[s] = self.counts.get(s, 0) + t
self._refresh(s)
def _update(self, node, s):
cand = [x for x in node.top if x != s]
cand.append(s)
cand.sort(key=lambda x: (-self.counts[x], x))
node.top = cand[:3]
def _refresh(self, s):
node = self.root
self._update(node, s)
for ch in s:
node = node.children.setdefault(ch, TrieNode())
self._update(node, s)
def input(self, c: str) -> List[str]:
if c == '#':
s = self.prefix
self.counts[s] = self.counts.get(s, 0) + 1
self._refresh(s)
self.prefix = ""
return []
self.prefix += c
node = self.root
for ch in self.prefix:
node = node.children.get(ch)
if node is None:
return []
return list(node.top)
JavaTested in our runner
import java.util.*;
class AutocompleteSystem {
static class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
List<String> top = new ArrayList<>();
}
private TrieNode root = new TrieNode();
private Map<String, Integer> counts = new HashMap<>();
private 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);
refresh(sentences[i]);
}
}
private void update(TrieNode node, String s) {
List<String> cand = new ArrayList<>();
for (String x : node.top) {
if (!x.equals(s)) cand.add(x);
}
cand.add(s);
cand.sort((a, b) -> {
int ca = counts.get(a), cb = counts.get(b);
if (ca != cb) return cb - ca;
return a.compareTo(b);
});
node.top = new ArrayList<>(cand.subList(0, Math.min(3, cand.size())));
}
private void refresh(String s) {
TrieNode node = root;
update(node, s);
for (int i = 0; i < s.length(); i++) {
node = node.children.computeIfAbsent(s.charAt(i), k -> new TrieNode());
update(node, s);
}
}
public String[] input(String c) {
if (c.equals("#")) {
String s = prefix.toString();
counts.merge(s, 1, Integer::sum);
refresh(s);
prefix.setLength(0);
return new String[0];
}
prefix.append(c);
TrieNode node = root;
for (int i = 0; i < prefix.length(); i++) {
node = node.children.get(prefix.charAt(i));
if (node == null) return new String[0];
}
return node.top.toArray(new String[0]);
}
}
C++Tested in our runner
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class AutocompleteSystem {
struct TrieNode {
unordered_map<char, TrieNode*> children;
vector<string> top;
};
TrieNode* root;
unordered_map<string, int> counts;
string prefix;
void update(TrieNode* node, const string& s) {
vector<string> cand;
for (const string& x : node->top) {
if (x != s) cand.push_back(x);
}
cand.push_back(s);
sort(cand.begin(), cand.end(), [&](const string& a, const string& b) {
if (counts[a] != counts[b]) return counts[a] > counts[b];
return a < b;
});
if (cand.size() > 3) cand.resize(3);
node->top = cand;
}
void refresh(const string& s) {
TrieNode* node = root;
update(node, s);
for (char ch : s) {
if (!node->children.count(ch)) node->children[ch] = new TrieNode();
node = node->children[ch];
update(node, s);
}
}
public:
AutocompleteSystem(vector<string>& sentences, vector<int>& times) {
root = new TrieNode();
for (size_t i = 0; i < sentences.size(); ++i) {
counts[sentences[i]] += times[i];
refresh(sentences[i]);
}
}
vector<string> input(string c) {
if (c == "#") {
counts[prefix] += 1;
refresh(prefix);
prefix.clear();
return {};
}
prefix += c;
TrieNode* node = root;
for (char ch : prefix) {
auto it = node->children.find(ch);
if (it == node->children.end()) return {};
node = it->second;
}
return node->top;
}
};
JavaScriptTested in our runner
var AutocompleteSystem = function(sentences, times) {
this.root = { children: new Map(), top: [] };
this.counts = new Map();
this.prefix = "";
for (let i = 0; i < sentences.length; i++) {
this.counts.set(sentences[i], (this.counts.get(sentences[i]) || 0) + times[i]);
this.refresh(sentences[i]);
}
};
AutocompleteSystem.prototype.update = function(node, s) {
const cand = node.top.filter(x => x !== s);
cand.push(s);
cand.sort((a, b) => {
const ca = this.counts.get(a), cb = this.counts.get(b);
if (ca !== cb) return cb - ca;
return a < b ? -1 : (a > b ? 1 : 0);
});
node.top = cand.slice(0, 3);
};
AutocompleteSystem.prototype.refresh = function(s) {
let node = this.root;
this.update(node, s);
for (const ch of s) {
if (!node.children.has(ch)) {
node.children.set(ch, { children: new Map(), top: [] });
}
node = node.children.get(ch);
this.update(node, s);
}
};
/**
* @param {string} c
* @return {string[]}
*/
AutocompleteSystem.prototype.input = function(c) {
if (c === '#') {
this.counts.set(this.prefix, (this.counts.get(this.prefix) || 0) + 1);
this.refresh(this.prefix);
this.prefix = "";
return [];
}
this.prefix += c;
let node = this.root;
for (const ch of this.prefix) {
node = node.children.get(ch);
if (node === undefined) return [];
}
return node.top.slice();
};
GoTested in our runner
import "sort"
type trieNode struct {
children map[byte]*trieNode
top []string
}
type AutocompleteSystem struct {
root *trieNode
counts map[string]int
prefix []byte
}
func newNode() *trieNode {
return &trieNode{children: map[byte]*trieNode{}}
}
func (this *AutocompleteSystem) update(node *trieNode, s string) {
cand := []string{}
for _, x := range node.top {
if x != s {
cand = append(cand, x)
}
}
cand = append(cand, s)
sort.Slice(cand, func(i, j int) bool {
a, b := cand[i], cand[j]
if this.counts[a] != this.counts[b] {
return this.counts[a] > this.counts[b]
}
return a < b
})
if len(cand) > 3 {
cand = cand[:3]
}
node.top = cand
}
func (this *AutocompleteSystem) refresh(s string) {
node := this.root
this.update(node, s)
for i := 0; i < len(s); i++ {
next, ok := node.children[s[i]]
if !ok {
next = newNode()
node.children[s[i]] = next
}
node = next
this.update(node, s)
}
}
func Constructor(sentences []string, times []int) AutocompleteSystem {
sys := AutocompleteSystem{root: newNode(), counts: map[string]int{}}
for i, s := range sentences {
sys.counts[s] += times[i]
sys.refresh(s)
}
return sys
}
func (this *AutocompleteSystem) input(c string) []string {
if c == "#" {
s := string(this.prefix)
this.counts[s]++
this.refresh(s)
this.prefix = this.prefix[:0]
return []string{}
}
this.prefix = append(this.prefix, c[0])
node := this.root
for i := 0; i < len(this.prefix); i++ {
next, ok := node.children[this.prefix[i]]
if !ok {
return []string{}
}
node = next
}
return append([]string{}, node.top...)
}
C#Tested in our runner
public class AutocompleteSystem {
private class TrieNode {
public Dictionary<char, TrieNode> Children = new Dictionary<char, TrieNode>();
public List<string> Top = new List<string>();
}
private TrieNode root = new TrieNode();
private Dictionary<string, int> counts = new Dictionary<string, int>();
private string prefix = "";
public AutocompleteSystem(string[] sentences, int[] times) {
for (int i = 0; i < sentences.Length; i++) {
Bump(sentences[i], times[i]);
Refresh(sentences[i]);
}
}
private void Bump(string s, int k) {
counts.TryGetValue(s, out int v);
counts[s] = v + k;
}
private void Update(TrieNode node, string s) {
var cand = new List<string>();
foreach (var x in node.Top) {
if (x != s) cand.Add(x);
}
cand.Add(s);
cand.Sort((a, b) => {
int ca = counts[a], cb = counts[b];
if (ca != cb) return cb.CompareTo(ca);
return string.CompareOrdinal(a, b);
});
if (cand.Count > 3) cand.RemoveRange(3, cand.Count - 3);
node.Top = cand;
}
private void Refresh(string s) {
TrieNode node = root;
Update(node, s);
foreach (char ch in s) {
if (!node.Children.ContainsKey(ch)) node.Children[ch] = new TrieNode();
node = node.Children[ch];
Update(node, s);
}
}
public string[] input(string c) {
if (c == "#") {
Bump(prefix, 1);
Refresh(prefix);
prefix = "";
return new string[0];
}
prefix += c;
TrieNode node = root;
foreach (char ch in prefix) {
TrieNode next;
if (!node.Children.TryGetValue(ch, out next)) return new string[0];
node = next;
}
return node.Top.ToArray();
}
}
Common mistakes
- Refreshing only the leaf for '#' (for example
node.top.add(s)at the last node) leaves every prefix node above it with a stale top list, soamay not showabcafter it is saved. Refresh every node on the path. - Adding the sentence to a node's top list without removing the old copy first, as in
cand = node.top + [s], lists the same sentence twice after a second finish. Filterx != sbefore adding. - Writing
counts[s] += 1in Python without a default for missing keys raises a KeyError on the first save of a new sentence. Usecounts.get(s, 0) + 1. - Forgetting to clear the prefix after '#' makes the next sentence start with the old characters, so
abcfollowed bydwould look upabcd. - Returning the node's own list instead of a copy lets the caller change the cache. In Go, returning
node.topdirectly shares the backing array, so copy it first. - Sorting ties by length or in reverse order instead of ascending text. The tie rule is lexicographically smaller first, so
abcomes beforeabcat equal counts.
Edge cases
- '#' with an empty prefix right after construction: it stores the empty string with count 1 at the root. The root is never returned, because every call appends a letter before the lookup.
- A prefix that matches nothing, such as
zon a system holding onlyabc: the walk fails at the first missing child and returns an empty list. - Two sentences where one is a prefix of the other, such as
abandabc: the prefixabreturns both. The shorter one is listed first only when its count is higher or equal and it is lexicographically smaller. - Equal counts with different lengths, such as
a banda b c: the tie goes to the lexicographically smaller sentence, which is the shorter one here. - Spaces inside sentences:
a(with a trailing space) andaare different keys, and the space is a normal trie edge. - A sentence that the user types repeatedly past the top 3 cutoff: its count rises, and it moves up in each node's list without disturbing sentences that stay ranked above it.
Follow-ups interviewers ask
- What if the sentence history is far too large to fit in memory?
- Shard the trie by the first character or by a hash of the prefix, and keep each shard on its own machine. For each prefix, store the precomputed top 3 list in a key-value store, and batch count updates before writing them back. Reads stay one lookup per letter, and writes become asynchronous.
- What if frequencies can also go down, or sentences can be deleted?
- The top 3 shortcut depends on counts only going up. When a count drops, a sentence that was outside the top 3 can enter. The node must then be rebuilt from its subtree, or hold a heap per node with lazy deletion. The cost of an update then depends on the subtree size instead of the sentence length.
- Can you return the top k sentences for any k instead of 3?
- Yes. Keep the top k at each node instead of 3, so an update costs O(k log k) per node on the path. The lookup still costs O(p + k), and k is a small parameter in this design, so the total work stays low.
Design Search Autocomplete System FAQ
What is the time complexity of Design Search Autocomplete System?
A letter costs O(p) in the trie version, where p is the prefix length, because it walks p edges and copies at most 3 sentences. A '#' costs O(L^2) for a sentence of length L, because each of the L + 1 nodes on the path sorts at most 4 strings. The brute force version costs O(N * L) per letter, where N is the number of stored sentences.
Why use a trie for Design Search Autocomplete System?
A trie puts every sentence with the same prefix under one node, so a lookup walks only the prefix and does not scan other sentences. Storing the best 3 sentences at each node means the answer is ready once the walk ends. The trie is the structure that makes the per-letter cost depend on the prefix length, not the history size.
Can Design Search Autocomplete System be solved in O(1) extra space?
No, not beyond the data the system must keep. The trie holds one node per distinct prefix, so its size grows with the total number of characters. Each node adds at most 3 references to the top list, which is constant per node but still proportional to the trie size.
Does the '#' input add the sentence when the prefix is empty?
Yes, in the trie version the empty string is stored at the root with its count. The empty string never appears in a result, because every lookup first appends a letter and so never returns the root's list.
Asked at
See which companies ask this — Pro
Related problems
- Find Median from Data Stream · same technique: Design (General/Specific)
- LFU Cache · same technique: Design (General/Specific)
- All O`one Data Structure · same technique: Design (General/Specific)
- Word Squares · same technique: Design (General/Specific)
- Design a Text Editor · same pattern: Design Patterns
- Prefix and Suffix Search · same pattern: Design Patterns
- Range Module · same pattern: Design Patterns
- LRU Cache · same pattern: Design Patterns
- Min Stack · same pattern: Design Patterns
- Time Based Key-Value Store · same pattern: Design Patterns