15% off all plans & roadmaps Use code

See plans

Design Search Autocomplete System

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 character c.
    • If c is not '#', append c to 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 c is '#', 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.

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.length
  • 1 <= n <= 100
  • 1 <= sentences[i].length <= 100
  • 1 <= times[i] <= 50
  • Each sentence consists of lowercase letters and spaces.
  • The input character c is a lowercase letter, a space ' ', or '#'.
  • The total number of characters input via input will 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Store each sentence in a dictionary and add its times to the count.
  2. Set the current prefix to the empty string.
  3. On a letter, append it to the prefix and scan every key in the dictionary.
  4. Keep the keys that start with the prefix.
  5. Sort the kept keys by count descending, then by text ascending.
  6. Return the first 3 keys.
  7. 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 becomes a. The scan finds no keys, so the result is [].
  • Call 2, letter b: the prefix becomes ab. The scan finds no keys, so the result is [].
  • Call 3, letter c: the prefix becomes abc. The scan finds no keys, so the result is [].
  • Call 4, #: the dictionary gets the key abc with count 1. The prefix resets to empty and the result is [].

The output is [[], [], [], []], which matches the example.

Complexity

TimeO(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
SpaceO(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]

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 infographic

Solution 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

  1. Create a root node with an empty child map and an empty top list.
  2. For each initial sentence, add its times to a count map and refresh that sentence along its path.
  3. 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.
  4. On a letter, append it to the prefix and follow the child for that letter. If a child is missing, return an empty list.
  5. At the node you reach, return a copy of its top list.
  6. 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.

StepInputPrefix after stepWalk resultTop lists after stepReturned
0init, no sentences(empty)root onlyroot: []n/a
1aano child 'a' under root, walk stopsroot: [][]
2babno child 'a' under root, walk stopsroot: [][]
3cabcno child 'a' under root, walk stopsroot: [][]
4#(empty)creates nodes a, ab, abc; counts abc = 1; refresh pathroot, 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

TimeO(p) per letter, where p is the prefix length; O(L^2) per '#' or sentence refresh, where L is the sentence length
SpaceO(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)

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, so a may not show abc after 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. Filter x != s before adding.
  • Writing counts[s] += 1 in Python without a default for missing keys raises a KeyError on the first save of a new sentence. Use counts.get(s, 0) + 1.
  • Forgetting to clear the prefix after '#' makes the next sentence start with the old characters, so abc followed by d would look up abcd.
  • Returning the node's own list instead of a copy lets the caller change the cache. In Go, returning node.top directly 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 ab comes before abc at 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 z on a system holding only abc: 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 ab and abc: the prefix ab returns 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 b and a b c: the tie goes to the lexicographically smaller sentence, which is the shorter one here.
  • Spaces inside sentences: a (with a trailing space) and a are 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

Practise it