---
title: "Trie (Prefix Tree) Data Structure Explained"
url: https://www.khanwaseem.com/blog/data-structure-and-algorithm/trie-data-structure
author: "khan Waseem"
published: 2026-11-29
updated: 2026-11-29
topics: ["Data Structure and Algorithm", "Blog"]
description: "Learn the trie (prefix tree), the data structure behind autocomplete and spell checkers: how it stores words letter by letter, how to insert, search, autocomplete, count and delete, plus longest common prefix and word…"
---

# Trie (Prefix Tree) Data Structure Explained

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [Part 1: How a Trie Works](#part-1-how-a-trie-works)[1. The Idea:](#1-the-idea)
- [2. Why the End Marker Matters:](#2-why-the-end-marker-matters)
- [3. The Node:](#3-the-node)

- [Part 2: Building the Trie](#part-2-building-the-trie)[4. Insert:](#4-insert)
- [5. Search and Prefix Check:](#5-search-and-prefix-check)
- [6. Counting Words with a Prefix:](#6-counting-words-with-a-prefix)

- [Part 3: Autocomplete](#part-3-autocomplete)[7. Collecting All Words Below a Node:](#7-collecting-all-words-below-a-node)
- [8. How Fast Is It in Practice?:](#8-how-fast-is-it-in-practice)

- [Part 4: Deleting a Word](#part-4-deleting-a-word)[9. Delete:](#9-delete)

- [Part 5: Classic Problems](#part-5-classic-problems)[10. Longest Common Prefix:](#10-longest-common-prefix)
- [11. Word Break:](#11-word-break)

- [Part 6: Trade-offs](#part-6-trade-offs)[12. Complexity:](#12-complexity)
- [13. Trie vs Hash Table:](#13-trie-vs-hash-table)
- [14. Where Tries Are Used:](#14-where-tries-are-used)

- [Conclusion:](#conclusion)

## Introduction:

When you start typing “car” into a search box, it instantly suggests “card”, “care” and “careful”. Your phone’s keyboard does the same thing for every word you type, and a code editor does it for every variable name. How do these programs find all the words that **start with** what you typed, out of hundreds of thousands, in a fraction of a millisecond?

A very common answer is a **trie** (usually pronounced “try”), also called a **prefix tree**. It is a tree that stores words **letter by letter**, so that all words sharing the same beginning also share the same path in the tree.

In this lesson we will learn how a trie is built, then implement one in JavaScript with insert, search, prefix check, autocomplete, prefix counting and delete. After that we will solve two classic interview problems with it and compare it with a [hash table](https://blog.khanwaseem.com/hash-table-data-structure/). It builds on the [binary tree](https://blog.khanwaseem.com/binary-tree-and-binary-search-tree/) and [recursion](https://blog.khanwaseem.com/recursion-in-data-structures-and-algorithms/) lessons.

All code was run with Node.js, and the comments show the real output.

## Part 1: How a Trie Works

### 1. The Idea:

Imagine a paper dictionary. To find “care”, you first go to the **C** section, then to the pages starting with **CA**, then **CAR**, and so on. Each letter narrows the search. A trie turns that idea into a tree:

- The **root** is empty and represents the start of every word.

- Each **edge** is labelled with one character.

- Following edges from the root spells out a word, letter by letter.

- A node is **marked** when a complete word ends there.

Here is a trie holding `car`, `card`, `care`, `careful`, `cat`, `dog` and `dot`. A `*` marks the end of a word:

```javascript
(root)
 ├─ c
 │  └─ a
 │     ├─ r *              "car"
 │     │  ├─ d *           "card"
 │     │  └─ e *           "care"
 │     │     └─ f─u─l *    "careful"
 │     └─ t *              "cat"
 └─ d
    └─ o
       ├─ g *              "dog"
       └─ t *              "dot"Code language: JavaScript (javascript)
```

Notice that `car`, `card`, `care` and `careful` all share the path `c → a → r`. The shared start, the **prefix**, is stored only once. And to find every word starting with “car”, we just walk three steps and then collect everything below that node.

### 2. Why the End Marker Matters:

The path `c → a` exists in our trie, but “ca” is not a word we inserted. The path alone can’t tell us that. This is why each node needs an `isEnd` flag. Similarly, “car” is a word **and** a prefix of “card”, so the `r` node has children and is also marked as an end.

### 3. The Node:

Each node stores its children and the end marker. We will also keep a `count` of how many words pass through the node, which makes prefix counting and deletion easy:

```javascript
class TrieNode {
  constructor() {
    this.children = new Map();   // char -> TrieNode
    this.isEnd = false;          // does a word end here?
    this.count = 0;              // how many words pass through this node
  }
}Code language: JavaScript (javascript)
```

We use a `Map` for the children so the trie works with any characters, including capitals, digits and Hindi or emoji characters. If you know the words only contain `a` to `z`, an array of 26 slots is a common alternative that is slightly faster but uses more memory per node.

## Part 2: Building the Trie

### 4. Insert:

To insert a word, start at the root and follow the edge for each character, **creating** a node whenever one is missing. At the last character, mark the node as an end:

```javascript
class Trie {
  constructor() {
    this.root = new TrieNode();
    this.size = 0;               // number of words stored
  }

  insert(word) {
    if (this.has(word)) return false;   // ignore duplicates
    let node = this.root;
    for (const ch of word) {
      if (!node.children.has(ch)) node.children.set(ch, new TrieNode());
      node = node.children.get(ch);
      node.count++;
    }
    node.isEnd = true;
    this.size++;
    return true;
  }
}Code language: JavaScript (javascript)
```

Inserting a word of length **L** takes **O(L)** time. It doesn’t matter whether the trie holds ten words or ten million; we only ever look at one node per character.

### 5. Search and Prefix Check:

Both operations walk down the tree one character at a time, so we share a small private helper. It returns the node where the text ends, or `null` if the path breaks:

```php
  #walk(text) {
    let node = this.root;
    for (const ch of text) {
      node = node.children.get(ch);
      if (!node) return null;
    }
    return node;
  }

  has(word) {
    const node = this.#walk(word);
    return node !== null && node.isEnd;
  }

  startsWith(prefix) {
    return this.#walk(prefix) !== null;
  }Code language: PHP (php)
```

The only difference: `has` also checks the end marker, while `startsWith` only needs the path to exist.

```javascript
const t = new Trie();
for (const w of ["car", "card", "care", "careful", "cat", "dog", "dot"]) t.insert(w);

console.log(t.size);                                   // 7
console.log(t.has("car"), t.has("ca"));                // true false
console.log(t.startsWith("ca"), t.startsWith("cow"));  // true false
console.log(t.insert("car"));                          // false (already there)Code language: JavaScript (javascript)
```

Both run in **O(L)** time, where L is the length of the word or prefix.

### 6. Counting Words with a Prefix:

Because each node knows how many words pass through it, counting the words that start with a prefix is just a walk plus one lookup:

```php
  countPrefix(prefix) {
    if (prefix === "") return this.size;
    const node = this.#walk(prefix);
    return node ? node.count : 0;
  }

console.log(t.countPrefix("car"));   // 4  (car, card, care, careful)
console.log(t.countPrefix("do"));    // 2  (dog, dot)Code language: PHP (php)
```

This is useful for things like “show how many products match” while the user is still typing.

## Part 3: Autocomplete

### 7. Collecting All Words Below a Node:

Autocomplete is where the trie really shines. Walk to the node for the prefix, then do a **depth-first search** below it, collecting every word you pass. Visiting children in sorted order gives results in alphabetical order, and a `limit` stops the search early:

```php
  autocomplete(prefix, limit = Infinity) {
    const start = this.#walk(prefix);
    const results = [];
    if (!start) return results;

    const dfs = (node, path) => {
      if (results.length >= limit) return;
      if (node.isEnd) results.push(path);
      const keys = [...node.children.keys()].sort();
      for (const ch of keys) dfs(node.children.get(ch), path + ch);
    };

    dfs(start, prefix);
    return results;
  }

console.log(t.autocomplete("car"));     // [ 'car', 'card', 'care', 'careful' ]
console.log(t.autocomplete("ca", 3));   // [ 'car', 'card', 'care' ]
console.log(t.autocomplete("x"));       // []Code language: PHP (php)
```

The time is **O(P + K)**, where P is the prefix length and K is the size of the part of the tree below the prefix that we actually visit. With a limit, the search stops as soon as it has enough suggestions, which is exactly what a search box wants.

### 8. How Fast Is It in Practice?:

To see the difference, we inserted **200,000** usernames (`user0`, `user1`, … in base 36) and asked for the first five that start with `user1a`, once with the trie and once by filtering and sorting the plain array:

```javascript
const words = [];
for (let i = 0; i < 200000; i++) words.push("user" + i.toString(36));

const big = new Trie();
words.forEach((w) => big.insert(w));

big.autocomplete("user1a", 5);
// [ 'user1a', 'user1a0', 'user1a00', 'user1a01', 'user1a02' ]   0.03 ms

words.filter((w) => w.startsWith("user1a")).sort().slice(0, 5);
// same five words                                                5.81 msCode language: JavaScript (javascript)
```

Both gave the same answer, but the trie was roughly **190 times faster**, because it never looked at the other 199,000+ words. The array approach must check every word on every keystroke. Exact times depend on your machine, but the gap grows as the word list grows.

## Part 4: Deleting a Word

### 9. Delete:

Deleting has two cases:

- **The word is a prefix of another word** (deleting “car” while “card” exists). We must keep the nodes and just clear the `isEnd` flag.

- **Part of the word’s path is used by no other word** (deleting “careful”). We should remove those nodes so the trie doesn’t fill up with dead branches.

The `count` field makes this simple. Walk down, decreasing each count. The first time a count reaches zero, no other word uses that branch, so we cut it off right there:

```javascript
  delete(word) {
    if (!this.has(word)) return false;
    let node = this.root;
    for (const ch of word) {
      const next = node.children.get(ch);
      next.count--;
      if (next.count === 0) {          // no other word uses this branch
        node.children.delete(ch);
        this.size--;
        return true;
      }
      node = next;
    }
    node.isEnd = false;                // word was a prefix of another word
    this.size--;
    return true;
  }Code language: JavaScript (javascript)
```

```javascript
console.log(t.delete("car"), t.has("car"), t.has("card"));   // true false true
console.log(t.delete("careful"), t.autocomplete("car"));     // true [ 'card', 'care' ]
console.log(t.delete("dog"), t.autocomplete("do"), t.size);  // true [ 'dot' ] 4Code language: JavaScript (javascript)
```

After deleting “careful”, the `f → u → l` branch is gone completely, and we checked that the `e` node no longer has an `f` child. Delete is also **O(L)**.

## Part 5: Classic Problems

### 10. Longest Common Prefix:

Given a list of words, find the longest prefix they all share. Insert them into a trie, then walk down from the root **as long as there is exactly one child and no word ends**. The moment the path splits or a word ends, we stop:

```javascript
function longestCommonPrefix(words) {
  const trie = new Trie();
  for (const w of words) trie.insert(w);

  let node = trie.root, prefix = "";
  while (node.children.size === 1 && !node.isEnd) {
    const [ch, next] = node.children.entries().next().value;
    prefix += ch;
    node = next;
  }
  return prefix;
}

console.log(longestCommonPrefix(["flower", "flow", "flight"]));          // "fl"
console.log(longestCommonPrefix(["interview", "internet", "interval"])); // "inter"
console.log(longestCommonPrefix(["dog", "racecar"]));                    // ""
console.log(longestCommonPrefix(["car", "card"]));                       // "car"Code language: JavaScript (javascript)
```

The `!node.isEnd` check matters for the last case: “car” ends at the `r` node, so the common prefix can’t go further, even though `r` has only one child.

### 11. Word Break:

Can a string be split into words from a dictionary? For example, “applepenapple” is “apple” + “pen” + “apple”. This is a [dynamic programming](https://blog.khanwaseem.com/dynamic-programming/) problem, and a trie makes the inner step fast. `ok[i]` means “the first i characters can be split”. From every position that is reachable, we walk the trie forward and mark every place a dictionary word ends:

```javascript
function wordBreak(s, words) {
  const trie = new Trie();
  for (const w of words) trie.insert(w);

  const ok = new Array(s.length + 1).fill(false);
  ok[0] = true;

  for (let i = 0; i < s.length; i++) {
    if (!ok[i]) continue;
    let node = trie.root;
    for (let j = i; j < s.length; j++) {
      node = node.children.get(s[j]);
      if (!node) break;               // no dictionary word continues this way
      if (node.isEnd) ok[j + 1] = true;
    }
  }
  return ok[s.length];
}

console.log(wordBreak("applepenapple", ["apple", "pen"]));                    // true
console.log(wordBreak("catsandog", ["cats", "dog", "sand", "and", "cat"]));  // falseCode language: JavaScript (javascript)
```

The trie lets us stop the inner loop as soon as no word can continue, instead of trying every possible substring against a list.

## Part 6: Trade-offs

### 12. Complexity:

For a word or prefix of length L:

- **Insert:** O(L)

- **Search (has):** O(L)

- **Prefix check (startsWith):** O(L)

- **Count words with a prefix:** O(L), thanks to the `count` field

- **Autocomplete:** O(L + size of the subtree visited)

- **Delete:** O(L)

- **Space:** O(total characters of all words) in the worst case, less when words share prefixes

The important thing is that none of these depend on **how many words** are stored, only on the length of the word you are working with.

### 13. Trie vs Hash Table:

A hash table (or a JavaScript `Set`) can also check whether a word exists in O(L) time on average, since it must hash all L characters. So why use a trie?

- **Prefix queries:** a hash table has no idea which keys start with “car”. It would have to check every key. A trie answers this naturally.

- **Sorted output:** walking a trie in order gives words alphabetically for free. A hash table has no order.

- **Shared storage:** common prefixes are stored once. Our five words `inter`, `internal`, `internet`, `interval` and `interview` have **38 characters** in total but the trie needs only **16 nodes**.

The trie’s weakness is **memory per node**. Every node is an object with its own map, which is much heavier than one character in a string. For a few thousand words that is irrelevant, but for very large dictionaries, programs use compressed variants such as a **radix tree** (Patricia trie), which merges chains of single-child nodes into one edge like `f─u─l` in our diagram.

If you only ever need “does this exact word exist?”, use a `Set`. If you need anything involving **prefixes**, a trie is usually the better tool.

### 14. Where Tries Are Used:

- **Autocomplete and search suggestions** in search boxes, IDEs and phone keyboards.

- **Spell checkers**, which walk the trie to find close matches for a misspelled word.

- **IP routing:** routers find the **longest matching prefix** of an IP address using a binary trie of address bits.

- **Word games** like Boggle and crossword solvers, which can stop exploring a path as soon as no word starts with it.

- **Text search** algorithms like Aho-Corasick, which search for many patterns at once using a trie with extra links.

## Conclusion:

A trie stores words character by character so that words with the same beginning share the same path. That makes insert, search, prefix checks, counting and delete all run in time proportional to the **length of the word**, not the number of words stored. We built a complete trie in JavaScript, used it for autocomplete that was about 190 times faster than filtering an array of 200,000 words, and solved the longest common prefix and word break problems with it. We also saw its main cost, memory per node, and how compressed radix trees reduce it.

In the next lesson we will explore **Breadth-First Search (BFS) and Depth-First Search (DFS)**, the two fundamental ways to walk through trees and graphs.

### Related posts:

[CSS – Text](https://blog.khanwaseem.com/css-text/)
[Binary Tree and Binary Search Tree](https://blog.khanwaseem.com/binary-tree-and-binary-search-tree/)
[Recursion Explained with Examples](https://blog.khanwaseem.com/recursion-in-data-structures-and-algorithms/)
[JavaScript – Promises and async/await](https://blog.khanwaseem.com/javascript-promises-and-async-await/)

Powered by [YARPP](https://yarpp.com).
