15% off all plans & roadmaps Use code

See plans

Implement Trie (Prefix Tree)

Updated

TL;DR: Build a data structure that stores words and answers exact-word and prefix queries. A trie stores one character per node, so every operation costs time proportional to the word length, not the number of stored words.

Problem

A trie (pronounced "try") or prefix tree is a tree data structure that stores and retrieves keys from a set of strings efficiently. Typical uses include autocomplete and spell checking.

Implement the Trie class:

  • Trie() creates an empty trie.
  • void insert(String word) adds the string word to the trie.
  • boolean search(String word) returns true if word was inserted earlier, and false otherwise.
  • boolean startsWith(String prefix) returns true if some previously inserted word begins with prefix, and false otherwise.

Example 1

Input: ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output: [null, null, true, false, true, null, true]
Explanation:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app");     // returns true

Constraints

  • 1 <= word.length, prefix.length <= 2000
  • word and prefix consist only of lowercase English letters.
  • At most 3 * 10^4 calls in total are made to insert, search, and startsWith.

Constraints that matter

  • Words can be 2000 characters long, so any approach that does work proportional to the length squared per insert costs up to 4 million steps per call. With 3 * 10^4 calls that is too heavy in the worst case.
  • Up to 3 * 10^4 total calls means a scan over every stored word on each startsWith is the number to beat. A scan costs (stored words) * (prefix length) per query.
  • Only lowercase letters a to z appear, so each node can hold a fixed array of 26 child slots and index it with c - 'a'.
  • Calls are mixed in any order, so you cannot batch or sort the words up front. The structure must answer queries after every single insert.

View on LeetCode

Hints

Hint 1

This is a trie problem.

Hint 2

Keep every inserted word in a plain list.

Solution

Intuition

This is a trie problem. The giveaway is the startsWith method. Exact lookup is easy with a hash set, but a prefix query asks about the beginning of words, and a hash set has no notion of beginnings.

Picture a set of nested folders, one per letter, where opening a folder adds one letter to the prefix. The root is the outermost folder, and the isEnd flag is a sticky note marking that a complete word is filed there.

The move is to stop treating a word as one unit. Store it as a path of characters from a root node. Words that share a start share the first nodes of their paths, so app and apple use the same three nodes.

That shared structure answers both queries by walking. To check a prefix, follow its letters from the root. If every step finds a child, some inserted word passes through that node, so the prefix exists. If a step finds nothing, no word has that prefix.

Exact search needs one extra fact. Reaching the node for app only proves that app is a prefix of something. You also need a flag on the node saying a word ended there.

Insert apple and the nodes for a, p, p, l, e exist, but only the node for e has the flag. So search("app") fails and startsWith("app") succeeds. Each query walks at most one node per character, so cost depends on the query length and not on how many words are stored.

Watch the pattern animation

Worked example

Input: operations = ["Trie", "search", "startsWith"], arguments = [[], ["a"], ["a"]]
Output: [null, false, false]
Explanation: The constructor makes an empty trie. Nothing was inserted, so no word equals "a" and no word starts with "a". Both queries return false, and the constructor returns null.

Approach 1: Brute force: list of words

Keep every inserted word in a plain list. insert appends the word. search compares the query against each stored word. startsWith checks each stored word for the given prefix.

This is correct and takes only a few lines, so it is where a beginner starts. It ignores the fact that words share beginnings, which is exactly the structure the problem asks you to use.

Steps

  1. Create an empty list words in the constructor.
  2. In insert, append the word to the list.
  3. In search, loop over words and return true if any entry equals the query.
  4. In startsWith, loop over words and return true if any entry begins with the prefix.
  5. Return false when the loop finishes without a match.

Dry run

Trace the example. The constructor sets words = [].

  • search("a"): the loop body never runs because the list is empty. Return false.
  • startsWith("a"): same empty loop. Return false.

The output is [null, false, false]. With apple inserted first, startsWith("app") would compare app against apple, find a match on the first entry, and return true. A miss has to look at every stored word.

Complexity

TimeO(1) insert, O(N * L) search and startsWith
SpaceO(N * L)

Let N be the number of stored words and L the length of the longest string involved. insert appends once, which is O(1) amortized. search and startsWith visit up to N words and each comparison costs up to L characters, so one query costs O(N * L). Storage holds every word in full, which is O(N * L) characters. With 3 * 10^4 calls and 2000-character words this approach can reach billions of character comparisons.

PythonTested in our runner

from typing import List, Optional

class Trie:
    def __init__(self):
        self.words = []

    def insert(self, word: str) -> None:
        self.words.append(word)

    def search(self, word: str) -> bool:
        for w in self.words:
            if w == word:
                return True
        return False

    def startsWith(self, prefix: str) -> bool:
        for w in self.words:
            if w.startswith(prefix):
                return True
        return False

Approach 2: Two hash sets: words and prefixes

What's slow: the list forces every query to scan all stored words. A hash set would fix search, but startsWith still has no direct lookup.

The insight that fixes it: a prefix query is an exact lookup if you store every prefix. On insert, add the word to a words set and add each of its prefixes to a prefixes set. Both queries become one hash lookup.

The cost moves to insert. Each of the L prefixes is a new string of up to L characters, so you pay for building and hashing them.

Steps

  1. Create two empty hash sets, words and prefixes, in the constructor.
  2. In insert, add the whole word to words.
  3. In insert, loop i from 1 to the word length and add the first i characters to prefixes.
  4. In search, return whether words contains the query.
  5. In startsWith, return whether prefixes contains the query.

Dry run

Trace the example on an empty structure.

  • Constructor: words = {}, prefixes = {}.
  • search("a"): "a" is not in words. Return false.
  • startsWith("a"): "a" is not in prefixes. Return false.

The output is [null, false, false]. For comparison, insert("app") would put app in words and a, ap, app in prefixes. After that startsWith("ap") is a single lookup.

Complexity

TimeO(L^2) insert, O(L) search and startsWith
SpaceO(S), where S is the sum of L^2 over inserted words

Let L be the length of the word being processed. Insert creates L prefix strings of lengths 1 to L, which totals L * (L + 1) / 2 characters, so O(L^2) time and space per new word. Search and startsWith hash one string of length L, which costs O(L) and is independent of how many words are stored. Shared prefixes are stored once in the set, but a worst case of all-distinct words still needs O(L^2) characters each.

PythonTested in our runner

from typing import List, Optional

class Trie:
    def __init__(self):
        self.words = set()
        self.prefixes = set()

    def insert(self, word: str) -> None:
        self.words.add(word)
        for i in range(1, len(word) + 1):
            self.prefixes.add(word[:i])

    def search(self, word: str) -> bool:
        return word in self.words

    def startsWith(self, prefix: str) -> bool:
        return prefix in self.prefixes
Tries pattern infographic for Implement Trie (Prefix Tree)

Solution pattern

Tries

Part of Design Patterns

Approach 3: Trie with 26 child slotsOptimalTries

What's slow: the two-set version stores a, ap, app, appl, apple as five separate strings. The prefix app is copied into every longer prefix, which costs O(L^2) per insert.

The insight that fixes it: store each character once, in a tree. A node represents one prefix, and its 26 child slots point to the node for that prefix plus one letter. Moving down one level appends one character, so no string is ever copied.

Each node also carries an isEnd flag. It is set on the node where an inserted word finishes. search needs the node to exist and the flag to be set. startsWith needs only the node to exist. A small helper that walks a string and returns the final node, or nothing, serves both queries.

Steps

  1. Define a node with children, an array of 26 empty slots, and a boolean isEnd set to false.
  2. Create one root node in the constructor. It stands for the empty prefix.
  3. In insert, start at the root. For each character, compute c - 'a', create the child if the slot is empty, and move into it.
  4. After the last character, set isEnd = true on the current node.
  5. Write a helper walk(s) that follows s from the root and returns the last node, or nothing if a slot is empty.
  6. In search, return true when walk(word) finds a node and its isEnd is true.
  7. In startsWith, return true when walk(prefix) finds a node.

Dry run

Trace the example. The constructor creates only the root, and all 26 of its slots are empty.

StepCallPositionSlot checkedResult
1Trie()root creatednonereturns null
2search("a")start at rootroot slot 0 (a) is emptywalk gives nothing, return false
3startsWith("a")start at rootroot slot 0 (a) is emptywalk gives nothing, return false

The output is [null, false, false].

For contrast, after insert("app") the root has a child at slot 0, that node has a child at slot 15 (p), and that node has a child at slot 15 again. The last node has isEnd = true. Then search("apple") reaches the last p node, finds slot 11 (l) empty, and returns false.

Complexity

TimeO(L) per operation
SpaceO(T * 26), where T is the total number of nodes created

Let L be the length of the word or prefix passed to the call. Each operation visits one node per character and does constant work at each, so insert, search and startsWith all run in O(L). Cost does not depend on how many words are stored.

Each insert creates at most L new nodes, so T is at most the total characters inserted. Every node holds 26 slots, which gives O(26 * T) space. Shared prefixes reduce T below the raw character count.

PythonTested in our runner

from typing import List, Optional

class TrieNode:
    def __init__(self):
        self.children = [None] * 26
        self.is_end = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        node = self.root
        for ch in word:
            i = ord(ch) - ord('a')
            if node.children[i] is None:
                node.children[i] = TrieNode()
            node = node.children[i]
        node.is_end = True

    def _walk(self, s: str):
        # Follow s from the root; return the last node or None.
        node = self.root
        for ch in s:
            node = node.children[ord(ch) - ord('a')]
            if node is None:
                return None
        return node

    def search(self, word: str) -> bool:
        node = self._walk(word)
        return node is not None and node.is_end

    def startsWith(self, prefix: str) -> bool:
        return self._walk(prefix) is not None

Common mistakes

  • Returning true from search as soon as the walk finishes, without reading isEnd. After inserting only apple, search("app") would wrongly pass. Return node != null && node.isEnd.
  • Forgetting to set isEnd = true after the insert loop. Every search then fails even for words you inserted. Set the flag on the final node, not on a node inside the loop.
  • Writing node.children[i] = new Node() on every step of insert, even when the slot is filled. This wipes out the subtree below, so inserting car after cat loses cat. Create a child only when the slot is empty.
  • Indexing with ord(ch) or c instead of c - 'a'. The array has 26 slots, so the index is out of range. Subtract the code of a every time.
  • Making startsWith check isEnd. Then startsWith("app") fails when only apple exists. A prefix query needs only that the node exists.
  • Dereferencing a missing child in the walk, for example reading node.children[i].children[j] without a null check. Test for an empty slot after every step and return early.

Edge cases

  • Query before any insert (the verified example): search("a") and startsWith("a") both return false because the root has no children.
  • Insert apple, then search("app") returns false and startsWith("app") returns true. The prefix node exists but has no end flag.
  • Insert app and then apple. Both search("app") and search("apple") return true, since the flag on the app node survives.
  • Insert the same word twice. The second insert follows existing nodes and sets the same flag again, so nothing breaks.
  • Query longer than any stored word: with only app inserted, search("apple") and startsWith("apple") both return false because the l slot is empty.
  • A single-character word of length 1 and a 2000-character word both work, since the loop is per character and has no recursion.

Follow-ups interviewers ask

How would you add a delete operation?
Walk to the word's final node and clear isEnd. Then, going back up the path, remove each node that has no children and no end flag. You need a parent pointer, a recursive walk, or a stack of the path. That frees memory while keeping other words that share the prefix.
What if the alphabet is large, such as Unicode, and 26-slot arrays waste memory?
Replace the child array with a hash map from character to node, created lazily. Each node then pays only for the children it has. Lookups stay O(1) on average, so the per-operation time is still O(L). The cost is a larger constant factor and less predictable memory layout.
How would you return all words that start with a prefix, for autocomplete?
Walk to the prefix node with the same helper. Then run a depth-first search from that node, building the string as you go and collecting it whenever you pass a node with isEnd set. The cost is O(L) for the walk plus the size of the subtree you visit.

Implement Trie (Prefix Tree) FAQ

What is the time complexity of Implement Trie (Prefix Tree)?

Insert, search and startsWith each take O(L), where L is the length of the word or prefix. The walk visits one node per character and does constant work per node. The number of stored words does not matter.

Why use a trie for Implement Trie (Prefix Tree)?

The prefix query is the reason. A trie stores shared beginnings once, so reaching the node for a prefix answers the question directly. A list needs a scan of all words, and a hash set has no way to ask about a beginning without storing every prefix.

What is the difference between a trie and a tree?

A tree is any connected structure of nodes with no cycles. A trie is a specific tree where each edge is labelled with a character and the path from the root spells a prefix. Its shape comes from the stored strings, and it is not sorted by node value like a binary search tree.

How do you implement a trie in Python?

Make a TrieNode with a children list of 26 slots, or a dict, and an is_end boolean. The Trie holds a root node. Insert walks the word and creates missing children, then sets is_end. A dict for children is shorter to write and works well when the alphabet is large.

Can Implement Trie (Prefix Tree) be solved in O(1) extra space?

No, if the structure must answer arbitrary queries later. The stored words have to live somewhere, so total memory grows with the input. Each individual search or startsWith can run with O(1) extra space, because the walk is iterative and keeps only one node pointer.

What is the difference between LeetCode 208 and the Trie II problem?

This problem only asks whether a word or prefix exists, so a boolean flag per node is enough. The Trie II variant counts how many times each word was inserted and supports erase. That needs a counter on each node in place of the flag, typically one for words ending there and one for words passing through.

Asked at

See which companies ask this — Pro

Practise it