Algo-Sim › Tries

Autocomplete (Prefix Search)

Medium · Tries · step through it in Java, Python and C++ on your own input

Build a trie from a word list, then return every word that starts with a prefix, in alphabetical order.

Problem

Given a list of words and a prefix, return every word that starts with prefix, in alphabetical order, the way a search box suggests completions. The words are first loaded into a trie.

Constraints

Edge cases to test

Follow-up questions

How do you return only the top 3 suggestions?
Store the best few words at each node while inserting (or sort and binary search the word list): O(L) per query (LC 1268).
How would you rank by popularity?
Keep a count per word and a small heap (or a cached top-k list) at each node.

Solution

Java

class Autocomplete {
    private static class Node {
        Node[] next = new Node[26];
        boolean end;
    }
    private final Node root = new Node();

    public Autocomplete(String[] words) {
        for (String w : words) insert(w);
    }

    public List<String> suggest(String prefix) {
        Node node = root;
        for (char c : prefix.toCharArray()) {
            node = node.next[c - 'a'];
            if (node == null) return List.of();
        }
        List<String> out = new ArrayList<>();
        collect(node, new StringBuilder(prefix), out);
        return out;
    }

    private void collect(Node node, StringBuilder path, List<String> out) {
        if (node.end) out.add(path.toString());
        for (char c = 'a'; c <= 'z'; c++) {
            Node child = node.next[c - 'a'];
            if (child == null) continue;
            path.append(c);
            collect(child, path, out);
            path.deleteCharAt(path.length() - 1);
        }
    }

    private void insert(String word) {
        Node node = root;
        for (char c : word.toCharArray()) {
            if (node.next[c - 'a'] == null) node.next[c - 'a'] = new Node();
            node = node.next[c - 'a'];
        }
        node.end = true;
    }
}

Python

class Node:
    def __init__(self):
        self.next = [None] * 26
        self.end = False


class Autocomplete:
    def __init__(self, words):
        self.root = Node()
        for w in words:
            self._insert(w)

    def suggest(self, prefix):
        node = self.root
        for c in prefix:
            node = node.next[ord(c) - ord("a")]
            if node is None:
                return []
        out = []
        self._collect(node, list(prefix), out)
        return out

    def _collect(self, node, path, out):
        if node.end:
            out.append("".join(path))
        for i, child in enumerate(node.next):
            if child is None:
                continue
            path.append(chr(ord("a") + i))
            self._collect(child, path, out)
            path.pop()

    def _insert(self, word):
        node = self.root
        for c in word:
            i = ord(c) - ord("a")
            if node.next[i] is None:
                node.next[i] = Node()
            node = node.next[i]
        node.end = True

C++

#include <bits/stdc++.h>
using namespace std;

class Autocomplete {
  public:
    class Node {
      public:
        vector<Node *> next = vector<Node *>(26, nullptr);
        bool end = false;
    };
    Node *root = new Node();

    Autocomplete(vector<string> &words) {
        for (string w : words)
            insert(w);
    }

    vector<string> suggest(string &prefix) {
        Node *node = root;
        for (char c : prefix) {
            node = node->next[c - 'a'];
            if (node == nullptr)
                return {};
        }
        vector<string> out = {};
        string path = prefix;
        collect(node, path, out);
        return out;
    }

    void collect(Node *node, string &path, vector<string> &out) {
        if (node->end)
            out.push_back(path);
        for (char c = 'a'; c <= 'z'; c++) {
            Node *child = node->next[c - 'a'];
            if (child == nullptr)
                continue;
            path.push_back(c);
            collect(child, path, out);
            path.pop_back();
        }
    }

    void insert(string &word) {
        Node *node = root;
        for (char c : word) {
            if (node->next[c - 'a'] == nullptr)
                node->next[c - 'a'] = new Node();
            node = node->next[c - 'a'];
        }
        node->end = true;
    }
};

More Tries problems