Reading history

Trie Data Structure in C: Insert, Search and Autocomplete

7 min read 1 views

Learn the trie (prefix tree) in C: inserting and searching words, counting prefixes, autocomplete with depth-first search, and memory trade-offs.

When you type “prog” into a search box and it immediately suggests “program” and “progress”, a trie (pronounced “try”, from retrieval) is often doing the work. A trie is a tree in which each edge represents one character, so words that share a beginning share the same path from the root. Looking up a word or a prefix takes time proportional to its length, no matter how many words are stored.

In this lesson you will learn

  • How a trie stores words character by character
  • Insert and search in O(length of the word)
  • Counting words with a given prefix
  • Listing all words with a prefix for autocomplete
  • The memory trade-off of tries

This lesson uses strings and dynamic memory.

Insert, Search and Prefix Count

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define ALPHA 26   /* lowercase a-z only */

struct TrieNode {
    struct TrieNode *child[ALPHA];
    bool is_end;          /* a word ends here */
    int pass;             /* how many words pass through this node */
};

static struct TrieNode *new_node(void) {
    struct TrieNode *n = calloc(1, sizeof *n);    /* calloc sets all children to NULL */
    if (!n) exit(1);
    return n;
}

void insert(struct TrieNode *root, const char *word) {
    struct TrieNode *cur = root;
    for (const char *p = word; *p; p++) {
        int i = *p - 'a';
        if (!cur->child[i]) cur->child[i] = new_node();
        cur = cur->child[i];
        cur->pass++;
    }
    cur->is_end = true;
}

static const struct TrieNode *walk(const struct TrieNode *root, const char *s) {
    const struct TrieNode *cur = root;
    for (const char *p = s; *p && cur; p++) cur = cur->child[*p - 'a'];
    return cur;
}

bool search(const struct TrieNode *root, const char *word) {
    const struct TrieNode *n = walk(root, word);
    return n && n->is_end;
}

int count_prefix(const struct TrieNode *root, const char *prefix) {
    const struct TrieNode *n = walk(root, prefix);
    return n ? n->pass : 0;
}

void free_trie(struct TrieNode *n) {
    if (!n) return;
    for (int i = 0; i < ALPHA; i++) free_trie(n->child[i]);
    free(n);
}

int main(void) {
    const char *words[] = {"car", "card", "care", "cat", "dog", "do"};
    struct TrieNode *root = new_node();
    for (int i = 0; i < 6; i++) insert(root, words[i]);

    const char *queries[] = {"car", "ca", "do", "dot"};
    for (int i = 0; i < 4; i++)
        printf("search(\"%s\") = %s\n", queries[i], search(root, queries[i]) ? "found" : "not found");

    const char *prefixes[] = {"ca", "car", "d", "x"};
    for (int i = 0; i < 4; i++)
        printf("words starting with \"%s\": %d\n", prefixes[i], count_prefix(root, prefixes[i]));

    free_trie(root);
    return 0;
}

Output

search("car") = found
search("ca") = not found
search("do") = found
search("dot") = not found
words starting with "ca": 4
words starting with "car": 3
words starting with "d": 2
words starting with "x": 0
  • Each node has 26 child pointers, one per lowercase letter. The index is ch - 'a', so ‘a’ is 0 and ‘z’ is 25.
  • calloc allocates a node with every pointer set to NULL and the flags set to 0.
  • insert walks down letter by letter, creating missing nodes, and marks the last node with is_end. “car”, “card” and “care” share the nodes c → a → r.
  • search("ca") reaches a node, but it is not the end of any word, so the answer is “not found”. This is the difference between a word and a prefix.
  • The pass counter records how many words go through each node, so counting words that start with a prefix needs only a walk to the end of the prefix: 4 words start with “ca”.

Autocomplete

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

/* Autocomplete: list every word that begins with a prefix, in alphabetical order */
#define ALPHA 26
struct TrieNode { struct TrieNode *child[ALPHA]; bool is_end; };

static struct TrieNode *node(void) {
    struct TrieNode *n = calloc(1, sizeof *n);
    if (!n) exit(1);
    return n;
}
static void insert(struct TrieNode *root, const char *w) {
    for (; *w; w++) {
        int i = *w - 'a';
        if (!root->child[i]) root->child[i] = node();
        root = root->child[i];
    }
    root->is_end = true;
}

/* Depth-first walk that builds words in buf */
static void collect(const struct TrieNode *n, char *buf, int depth) {
    if (n->is_end) { buf[depth] = '\0'; printf("  %s\n", buf); }
    for (int i = 0; i < ALPHA; i++) {
        if (n->child[i]) {
            buf[depth] = (char)('a' + i);
            collect(n->child[i], buf, depth + 1);
        }
    }
}

static void autocomplete(const struct TrieNode *root, const char *prefix) {
    char buf[64];
    int depth = 0;
    const struct TrieNode *cur = root;
    for (const char *p = prefix; *p; p++) {
        cur = cur->child[*p - 'a'];
        if (!cur) { printf("\"%s\": no suggestions\n", prefix); return; }
        buf[depth++] = *p;
    }
    printf("\"%s\":\n", prefix);
    collect(cur, buf, depth);
}

static void free_trie(struct TrieNode *n) {
    if (!n) return;
    for (int i = 0; i < ALPHA; i++) free_trie(n->child[i]);
    free(n);
}

int main(void) {
    const char *dict[] = {"pro", "program", "programmer", "progress", "project",
                          "print", "private", "python"};
    struct TrieNode *root = node();
    for (int i = 0; i < 8; i++) insert(root, dict[i]);
    autocomplete(root, "prog");
    autocomplete(root, "pr");
    autocomplete(root, "java");
    free_trie(root);
    return 0;
}

Output

"prog":
  program
  programmer
  progress
"pr":
  print
  private
  pro
  program
  programmer
  progress
  project
"java": no suggestions
  • autocomplete first walks down the prefix. If a letter is missing, there are no suggestions.
  • collect then does a depth-first search from that node, writing letters into buf as it goes down and printing whenever it reaches a word end.
  • Children are visited from ‘a’ to ‘z’, so the suggestions come out in alphabetical order automatically, with no sorting needed. “pro” itself is listed because it is a complete word.

Trie vs Other Structures

TaskTrieHash tableSorted array
Exact lookupO(L)O(L) averageO(L log n)
All words with a prefixO(L + results)Must scan every wordTwo binary searches
Alphabetical listingNatural DFS orderNeeds sortingAlready sorted
MemoryHigh (many pointers)ModerateLow

L is the word length and n the number of words. Tries power autocomplete, spell checkers, word games such as Boggle, and IP routing tables, which match the longest prefix of an address.

Common Mistakes

  1. Treating every reached node as a word; check is_end.
  2. Not validating characters: an uppercase letter or digit gives an index outside 0–25 and corrupts memory. Convert or reject such input first.
  3. Forgetting to free every node recursively.
  4. Using a fixed 26-pointer array for large alphabets such as Unicode; use a hash map or sorted list of children instead.

Practice Exercises

Exercise 1. Write longest_common_prefix for all words in the trie.

Show answer
/* Follow the single path while a node has exactly one child and is not a word end */
void longest_common_prefix(const struct TrieNode *root, char *out) {
    int len = 0;
    const struct TrieNode *cur = root;
    for (;;) {
        int only = -1, kids = 0;
        for (int i = 0; i < ALPHA; i++) if (cur->child[i]) { kids++; only = i; }
        if (kids != 1 || cur->is_end) break;
        out[len++] = (char)('a' + only);
        cur = cur->child[only];
    }
    out[len] = '\0';
}

Exercise 2. How many nodes (besides the root) does a trie need for “tea”, “ten” and “to”?

Show answer

5 nodes: t is shared by all three words, e is shared by “tea” and “ten”, then a, n and o are one node each. Storing the words separately would need 8 characters.

Frequently Asked Questions

How can I reduce a trie’s memory use?

Use a compressed trie (radix tree), which merges chains of single-child nodes into one edge labelled with several characters, or store children in a small list or map instead of a fixed array.

Can a trie delete words?

Yes. Clear the is_end flag, decrease the pass counts, and free nodes on the way back up that no longer belong to any word.

Summary

  • A trie stores words as paths of characters from the root.
  • Insert, search and prefix checks take O(length).
  • A DFS from a prefix node lists completions in alphabetical order.
  • Tries trade memory for very fast prefix queries.

Next: Union-Find (Disjoint Set) in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *