AlgoTales · Roadmap

Autocomplete

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Autocomplete walks the trie to the point reached by the letters typed, then lists words found below that point. Because everything under that point already starts with the typed letters, there is no filtering step at all.

Practical use cases

  • Web app: Search suggestions in a shopping app. A shopper types "iph" and instantly sees "iphone 15", "iphone charger" and "iphone case". The app walks I, P, H and then collects the first few words below that node. Showing 5 suggestions costs about the same whether the shop has 10,000 or 5 million products.
  • Web app: Email recipient suggestions. In a webmail compose box, typing "ra" suggests "raj@...", "rahul@...". The contacts were put in a trie once, so each keystroke only needs to step one letter deeper and read a handful of results, keeping typing smooth. Nothing is filtered or sorted per key press, so even a phone browser keeps up with fast typists.
  • System: Code editors and search engines. Editors suggest variable names and search engines suggest queries as you type. These features must answer in a few milliseconds, which is only possible by jumping straight to the typed prefix.

The story: Raju's Talking Menu Board

Raju's chai stall had grown. He now sold chai, cutting chai, masala chai, coffee, cold coffee, kachori and more. Customers shouted orders and Raju's young helper Kabir had to find the price on a long list. He would scan the list from the top for every single order.

Mira brought him a small tablet. As Kabir typed "ma", the screen showed masala chai, mathri, maska pav. Customers loved it; Kabir tapped the right one in two seconds. "How does it know?" Raju asked.

"It does not search the whole menu," said Mira. "The words are in a trie. Each key you press moves one box deeper. Whatever is hanging below that box is exactly what can still be typed. We just list those words, in order, and stop after a few."

That is autocomplete: walk to the prefix (cost: its length), then do a depth-first walk below it, trying children in alphabetical order, until you have k suggestions. The menu size does not slow it down.

How to spot this problem, and where you need it

As the user types, you must show a short list of matching completions immediately, and a database LIKE query or full scan on every keystroke makes the box lag.

Signs you need it

  • There is a text box that shows a dropdown of suggestions while typing.
  • Each keystroke fires a request or a loop through the entire dataset and the dropdown arrives late.
  • Only the first 5 or 10 matches are needed, not the full list.
  • The suggestions are all things that start with what has been typed.

Where to use it in a project

  • Search boxes for products, cities, stations and users.
  • Tag, mention (@name) and command-palette inputs in apps.

The solution

Keep the candidate words in a trie. When the user types, walk down the letters typed. From that node, explore below it (depth-first, or in order of popularity if you store a score) and stop as soon as you have collected enough suggestions, for example 5. Return those to the dropdown. Each new letter just moves one step deeper.

Payoff: Before: a 400 ms lag from scanning every product per keystroke. After: a few steps and 5 results ready, so the dropdown feels instant.

Explain it like I am 8

Typing letters is like walking down a road, one step per letter. When you stop, look ahead: every place you could still reach from here is a word that fits what you typed. Read out the first few of them.

How it works, step by step

  1. Walk the typed prefix. If a letter is missing, there are no suggestions.
  2. Stand on the prefix box. If it carries a flag, the prefix itself is a suggestion.
  3. Depth-first through its children, visiting letters in alphabetical order, building the word as you go.
  4. Whenever you reach a flagged box, add the word to the list.
  5. Stop as soon as you collected k suggestions (so that a short prefix like "a" does not scan the whole dictionary).

The code in four languages

PHP

<?php
class TrieNode {
    public array $kids = [];
    public bool $end = false;
}

class Autocomplete {
    private TrieNode $root;
    public function __construct() { $this->root = new TrieNode(); }

    public function add(string $w): void {
        $n = $this->root;
        foreach (str_split($w) as $ch) { $n->kids[$ch] ??= new TrieNode(); $n = $n->kids[$ch]; }
        $n->end = true;
    }

    public function suggest(string $prefix, int $k): array {
        $n = $this->root;
        foreach (str_split($prefix) as $ch) {            // 1) walk to the prefix
            if (!isset($n->kids[$ch])) { return []; }
            $n = $n->kids[$ch];
        }
        $out = [];
        $this->collect($n, $prefix, $k, $out);            // 2) look below it
        return $out;
    }

    private function collect(TrieNode $n, string $word, int $k, array &$out): void {
        if (count($out) >= $k) { return; }                // enough already
        if ($n->end) { $out[] = $word; }
        $letters = array_keys($n->kids);
        sort($letters);                                   // alphabetical order
        foreach ($letters as $ch) {
            $this->collect($n->kids[$ch], $word . $ch, $k, $out);
        }
    }
}

$a = new Autocomplete();
foreach (['dog', 'cub', 'cat', 'do', 'car'] as $w) { $a->add($w); }
echo 'c:  ' . implode(', ', $a->suggest('c', 10)) . PHP_EOL;
echo 'ca: ' . implode(', ', $a->suggest('ca', 10)) . PHP_EOL;
echo 'c (top 2): ' . implode(', ', $a->suggest('c', 2)) . PHP_EOL;
echo 'd:  ' . implode(', ', $a->suggest('d', 10)) . PHP_EOL;
echo 'dx: ' . count($a->suggest('dx', 10)) . ' found' . PHP_EOL;

JavaScript

class TrieNode {
  constructor() { this.kids = {}; this.end = false; }
}

class Autocomplete {
  constructor() { this.root = new TrieNode(); }

  add(w) {
    let n = this.root;
    for (const ch of w) { if (!n.kids[ch]) n.kids[ch] = new TrieNode(); n = n.kids[ch]; }
    n.end = true;
  }

  suggest(prefix, k) {
    let n = this.root;
    for (const ch of prefix) {                // 1) walk to the prefix
      if (!n.kids[ch]) return [];
      n = n.kids[ch];
    }
    const out = [];
    this.collect(n, prefix, k, out);          // 2) look below it
    return out;
  }

  collect(n, word, k, out) {
    if (out.length >= k) return;              // enough already
    if (n.end) out.push(word);
    for (const ch of Object.keys(n.kids).sort()) {   // alphabetical order
      this.collect(n.kids[ch], word + ch, k, out);
    }
  }
}

const a = new Autocomplete();
for (const w of ['dog', 'cub', 'cat', 'do', 'car']) a.add(w);
console.log('c:  ' + a.suggest('c', 10).join(', '));
console.log('ca: ' + a.suggest('ca', 10).join(', '));
console.log('c (top 2): ' + a.suggest('c', 2).join(', '));
console.log('d:  ' + a.suggest('d', 10).join(', '));
console.log('dx: ' + a.suggest('dx', 10).length + ' found');

Java

import java.util.*;

public class Main {
    static class TrieNode {
        Map<Character, TrieNode> kids = new HashMap<>();
        boolean end = false;
    }

    static class Autocomplete {
        private final TrieNode root = new TrieNode();

        void add(String w) {
            TrieNode n = root;
            for (char ch : w.toCharArray()) {
                n.kids.putIfAbsent(ch, new TrieNode());
                n = n.kids.get(ch);
            }
            n.end = true;
        }

        List<String> suggest(String prefix, int k) {
            TrieNode n = root;
            for (char ch : prefix.toCharArray()) {            // 1) walk to the prefix
                if (!n.kids.containsKey(ch)) return new ArrayList<>();
                n = n.kids.get(ch);
            }
            List<String> out = new ArrayList<>();
            collect(n, prefix, k, out);                       // 2) look below it
            return out;
        }

        private void collect(TrieNode n, String word, int k, List<String> out) {
            if (out.size() >= k) return;                      // enough already
            if (n.end) out.add(word);
            List<Character> letters = new ArrayList<>(n.kids.keySet());
            Collections.sort(letters);                        // alphabetical order
            for (char ch : letters) {
                collect(n.kids.get(ch), word + ch, k, out);
            }
        }
    }

    public static void main(String[] args) {
        Autocomplete a = new Autocomplete();
        for (String w : new String[]{"dog", "cub", "cat", "do", "car"}) a.add(w);
        System.out.println("c:  " + String.join(", ", a.suggest("c", 10)));
        System.out.println("ca: " + String.join(", ", a.suggest("ca", 10)));
        System.out.println("c (top 2): " + String.join(", ", a.suggest("c", 2)));
        System.out.println("d:  " + String.join(", ", a.suggest("d", 10)));
        System.out.println("dx: " + a.suggest("dx", 10).size() + " found");
    }
}

Go

package main

import (
	"fmt"
	"sort"
	"strings"
)

type TrieNode struct {
	kids map[rune]*TrieNode
	end  bool
}

func newTrieNode() *TrieNode { return &TrieNode{kids: map[rune]*TrieNode{}} }

type Autocomplete struct {
	root *TrieNode
}

func NewAutocomplete() *Autocomplete { return &Autocomplete{root: newTrieNode()} }

func (a *Autocomplete) Add(w string) {
	n := a.root
	for _, ch := range w {
		if n.kids[ch] == nil {
			n.kids[ch] = newTrieNode()
		}
		n = n.kids[ch]
	}
	n.end = true
}

func (a *Autocomplete) Suggest(prefix string, k int) []string {
	n := a.root
	for _, ch := range prefix { // 1) walk to the prefix
		if n.kids[ch] == nil {
			return nil
		}
		n = n.kids[ch]
	}
	var out []string
	collect(n, prefix, k, &out) // 2) look below it
	return out
}

func collect(n *TrieNode, word string, k int, out *[]string) {
	if len(*out) >= k { // enough already
		return
	}
	if n.end {
		*out = append(*out, word)
	}
	letters := make([]rune, 0, len(n.kids))
	for ch := range n.kids {
		letters = append(letters, ch)
	}
	sort.Slice(letters, func(i, j int) bool { return letters[i] < letters[j] }) // alphabetical order
	for _, ch := range letters {
		collect(n.kids[ch], word+string(ch), k, out)
	}
}

func main() {
	a := NewAutocomplete()
	for _, w := range []string{"dog", "cub", "cat", "do", "car"} {
		a.Add(w)
	}
	fmt.Println("c:  " + strings.Join(a.Suggest("c", 10), ", "))
	fmt.Println("ca: " + strings.Join(a.Suggest("ca", 10), ", "))
	fmt.Println("c (top 2): " + strings.Join(a.Suggest("c", 2), ", "))
	fmt.Println("d:  " + strings.Join(a.Suggest("d", 10), ", "))
	fmt.Println("dx:", len(a.Suggest("dx", 10)), "found")
}

Time: O(P + size of the part explored) · Extra space: O(depth). Walk the prefix (P steps), then visit only the boxes below it; stopping at k suggestions keeps it small.

Watch out for

  • Scanning the whole word list and filtering, which makes every key press slow.
  • Forgetting that the prefix itself can be a word ("do" before "dog").
  • Not limiting the number of results, so a one-letter prefix produces thousands of words.

Quick check

  1. What do you do after walking down the typed prefix?
    • Restart from the root
    • Explore the boxes below it and collect flagged words
    • Sort the entire dictionary
  2. Why try children in alphabetical order?
    • To get sorted suggestions
    • It is required for the trie to work
    • It makes the trie smaller
  3. Typed prefix has a missing letter in the trie. Suggestions?
    • All words
    • An empty list
    • An error