Skip to content
Concept ยท Data Structures and Algorithms

Trie Data Structure (Prefix Tree): Python Implementation and Autocomplete, With Output

Younus FardeenBy Younus FardeenUpdated 1 Dec 20268 min read
Short answer

A trie, or prefix tree, stores words one letter per node so that words sharing a prefix share a path. Insert, search and startswith each take O(L) time for a word of length L, independent of how many words are stored. That makes tries a natural fit for autocomplete and prefix lookups.

On this pageWhat a trie is and how it worksTrie implementation in PythonAutocomplete with a trieThe memory trade-off: trie vs hash setInterview problems and a trie solutionFrequently asked questions

This page is for learners preparing for interviews or building a search box. It gives a short trie in Python, an autocomplete that ranks suggestions by popularity, an honest measurement of how much memory a trie costs compared with a hash set, and the interview problems where a trie is the intended answer.

All code ran on Python 3.9 on 1 December 2026 and the output shown is the real output. Complexity statements follow Wikipedia's trie article. A trie is a special tree where each edge carries a character.

What a trie is and how it works

In a trie, the root is empty and each edge is one character. To store car, card and care, you walk c, a, r from the root and mark the node after r as the end of a word; card and care then continue from that node. Words that start the same share the same first nodes, so a prefix is a path, and "does anything start with ca?" is answered by walking two edges.

OperationWhat it doesTime for word length L
insert(word)Walk down, creating missing nodes, mark the endO(L)
search(word)Walk down and check the end markO(L)
startswith(prefix)Walk down; success if the path existsO(L)
Collect all words under a prefixWalk to the prefix, then depth-first search below itO(L + size of that subtree)

The costs depend on the length of the word, not on how many words are stored. A set lookup is also O(L) on average, because hashing a string reads all its characters, so the real difference is not lookup speed but what a trie can do that a set cannot: prefix queries and ordered walks.

Trie implementation in Python

The simplest version stores each node as a dictionary from character to child node, with the key $ marking the end of a word. It is short enough to write on a whiteboard.

class Trie:
    def __init__(self):
        self.root = {}                       # each node: dict of char -> child node
        self.END = "$"                       # marker key: a word ends here

    def insert(self, word):
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node[self.END] = True

    def _walk(self, prefix):
        node = self.root
        for ch in prefix:
            if ch not in node:
                return None
            node = node[ch]
        return node

    def search(self, word):                  # exact word?
        node = self._walk(word)
        return node is not None and self.END in node

    def starts_with(self, prefix):           # any word begins with prefix?
        return self._walk(prefix) is not None

t = Trie()
for w in ["car", "card", "care", "cat", "dog"]:
    t.insert(w)

print(t.search("car"), t.search("ca"), t.search("cart"))
print(t.starts_with("ca"), t.starts_with("do"), t.starts_with("x"))

Output:

True False False
True True False

The first line: car was inserted so it is found; ca is only a prefix, so search says False; cart was never inserted. The second line shows startswith is True for ca and do and False for x. The end marker is what separates search from startswith, and forgetting it is the most common bug. If you prefer classes, use a TrieNode with children and is_end fields; the logic is identical.

Autocomplete with a trie

Autocomplete is walk to the prefix, collect the words below it, then rank them. The demo stores search phrases with a popularity score and returns the top three suggestions for a prefix.

class Trie:
    def __init__(self):
        self.root = {}

    def insert(self, word, weight=1):
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node["$"] = weight                   # weight = how popular the word is

    def suggest(self, prefix, k=3):
        node = self.root
        for ch in prefix:
            if ch not in node:
                return []
            node = node[ch]
        found = []
        def dfs(n, path):                    # collect every word below this node
            for ch, child in n.items():
                if ch == "$":
                    found.append((-child, path))
                else:
                    dfs(child, path + ch)
        dfs(node, prefix)
        return [w for _, w in sorted(found)[:k]]

searches = {"python": 90, "python tutorial": 70, "python for loop": 40,
            "pycharm": 30, "pandas": 60, "java": 80, "javascript": 85}
t = Trie()
for q, w in searches.items():
    t.insert(q, w)

print(t.suggest("py"))
print(t.suggest("java"))
print(t.suggest("pan"))
print(t.suggest("zz"))

Output:

['python', 'python tutorial', 'python for loop']
['javascript', 'java']
['pandas']
[]

For java, javascript outranks java because its score is higher. This version collects every word under the prefix before ranking, which is fine for thousands of words but slow for a very short prefix over a huge dictionary. Production systems cache the top results at each node or limit the search; this page does not claim to describe how any particular company does it. Collecting words below a node is a depth-first search, the same walk used in BFS vs DFS.

The memory trade-off: trie vs hash set

Every node is an object with its own table of children, so tries cost more memory than a set of the same words. The next code measures both for 20,000 random eight-letter words using tracemalloc. Real words share prefixes and random strings share very few, so this is close to a worst case for a trie. It is deliberately unflattering.

import random, string, tracemalloc

random.seed(7)
letters = string.ascii_lowercase
words = ["".join(random.choice(letters) for _ in range(8)) for _ in range(20000)]

def mem(build):
    tracemalloc.start()
    obj = build()
    size = tracemalloc.get_traced_memory()[0]
    tracemalloc.stop()
    return obj, size

def make_set():
    return set(words)

def make_trie():
    root = {}
    for w in words:
        node = root
        for ch in w:
            node = node.setdefault(ch, {})
        node["$"] = True
    return root

s, set_bytes = mem(make_set)
t, trie_bytes = mem(make_trie)
print("words:", len(words), "| chars:", sum(map(len, words)))
print("set  KB:", set_bytes // 1024)
print("trie KB:", trie_bytes // 1024)
print("trie is", round(trie_bytes / set_bytes, 1), "times the set")

Output on that run:

words: 20000 | chars: 160000
set  KB: 2048
trie KB: 25725
trie is 12.6 times the set

Sharing prefixes does reduce nodes when words genuinely overlap. For six words starting with inter, the trie needs fewer letter nodes than the total letters:

words = ["internet", "internal", "interval", "interview", "interact", "intern"]
root, nodes = {}, 0
for w in words:
    n = root
    for ch in w:
        if ch not in n:
            n[ch] = {}
            nodes += 1
        n = n[ch]
    n["$"] = True
print("letters if stored separately:", sum(map(len, words)))
print("letter nodes in the trie:", nodes)

Output:

letters if stored separately: 47
letter nodes in the trie: 19
NeedHash set or dictTrie
Is this exact word present?Yes, simplest and smallerYes, but more memory
Words with a given prefixScan every word, O(N * L)Walk to the prefix, then only the matches
Words in alphabetical orderSort firstDepth-first walk, already ordered if children are visited in order
Memory for 20,000 random words, measured aboveAbout 2 MBAbout 25 MB with dict nodes
Best fitPlain membership tests (hashmap explained)Autocomplete, prefix match, IP routing, spell check

Memory-lean variants exist (compressed or radix tries, arrays instead of dicts for a fixed alphabet), but for interviews and small projects the dictionary trie is the right start. The number above depends on the Python version, so treat it as an order of magnitude, not a constant.

Interview problems and a trie solution

Tries appear in a fairly small set of problems. The code solves one of them, longest common prefix: insert all words, then walk down while a node has exactly one child and no word ends there.

# Interview problem: Word Search-lite. Longest common prefix of a list using a trie.
def longest_common_prefix(words):
    root = {}
    for w in words:
        node = root
        for ch in w:
            node = node.setdefault(ch, {})
        node["$"] = True
    prefix, node = "", root
    while len(node) == 1 and "$" not in node:   # one way forward and no word ends here
        ch = next(iter(node))
        prefix += ch
        node = node[ch]
    return prefix

print(repr(longest_common_prefix(["flower", "flow", "flight"])))
print(repr(longest_common_prefix(["dog", "racecar", "car"])))
print(repr(longest_common_prefix(["interview", "internet", "internal"])))

Output:

'fl'
''
'inter'
  1. Implement Trie (Prefix Tree): the exact code above, with a class wrapper
  2. Design Add and Search Words Data Structure: a trie with . as a wildcard, solved by recursion
  3. Word Search II: build a trie of the word list, then depth-first search the board and prune with the trie (see backtracking)
  4. Replace Words and Longest Word in Dictionary: prefix lookups
  5. Maximum XOR of Two Numbers in an Array: a trie over the bits of each number

Ten more tree questions are in DSA interview questions, and practice sites are listed in coding practice websites. Parent path: DSA learning path. Routers use a bit-level trie for IP lookups, shown on applications of tree.

Frequently asked questions

What is a trie data structure?

A trie, also called a prefix tree, is a tree where each node represents one character and the path from the root spells a prefix. Words that share a prefix share nodes. It supports insert, search and prefix queries in time proportional to the length of the word.

What is the time complexity of a trie?

Insert, search and startswith each take O(L), where L is the length of the word or prefix, regardless of how many words are stored. Space is O(total characters) in the worst case, since each character may need its own node.

How is a trie different from a hash set?

A hash set tests exact membership with less memory. A trie additionally answers prefix questions, such as all words starting with pre, without scanning every word, and can list words in order. The price is more memory, as the measurement above shows.

How does autocomplete use a trie?

The search box text is the prefix. The program walks the trie to that node and collects the words below it, then ranks them, for example by popularity. Ranking data is stored at the end-of-word nodes. Real systems add caching and limits on top.

How do you implement a trie in Python?

Store each node as a dictionary of child characters, plus a marker such as $ for end of word. Insert walks the word using setdefault. Search walks it and checks the marker. Startswith walks it and returns whether the path exists.

What is the difference between search and startswith in a trie?

Search returns True only if the whole word was inserted, which means the final node has the end-of-word mark. Startswith returns True if the path for the prefix exists at all, even if the prefix is not itself a stored word.

When should I not use a trie?

When you only need exact lookups, a dict or set is simpler and smaller. Also avoid a naive trie for huge alphabets or random strings with few shared prefixes, where memory grows quickly. Consider a sorted list with binary search or a compressed trie instead.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Concept

Tree data structure

Binary trees, BST, traversals, height and balance with tested code

7 min read
Explainer

HashMap explained

How hashing, buckets and collisions work, with Python, JS and Java.

4 min read
Concept

Applications of tree

File systems, DOM, B-tree, compilers, routers, Huffman with runnable code

6 min read