ADVANCED DATA STRUCTURES PROGRAM • LEVEL 15 — DIGITAL SEARCH TREES

Generate Autocomplete Suggestions from a Trie

Learn how to generate autocomplete suggestions from a trie using a clear C program.

AdvancedTrieDigital search

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
car
card
care
cat

COMPLETE C PROGRAM

Complete C implementation

ads-trie-autocomplete.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

struct Trie { struct Trie *child[26]; int terminal, pass; };
struct Trie *new_trie(void) { struct Trie *node = calloc(1, sizeof *node); if (!node) exit(EXIT_FAILURE); return node; }
void insert_word(struct Trie *root, const char *word) { for (int i = 0; word[i]; i++) { int index = word[i] - 'a'; if (!root->child[index]) root->child[index] = new_trie(); root = root->child[index]; root->pass++; } root->terminal = 1; }
struct Trie *walk(struct Trie *root, const char *word) { for (int i = 0; word[i] && root; i++) root = root->child[word[i] - 'a']; return root; }
void free_trie(struct Trie *root) { if (root) { for (int i = 0; i < 26; i++) free_trie(root->child[i]); free(root); } }
void print_words(struct Trie *root, char buffer[], int length) { if (!root) return; if (root->terminal) { buffer[length] = '\0'; puts(buffer); } for (int i = 0; i < 26; i++) if (root->child[i]) { buffer[length] = (char) ('a' + i); print_words(root->child[i], buffer, length + 1); } }

int main(void)
{
    const char *words[] = {"car", "card", "care", "cat", "dog"}; struct Trie *root = new_trie(); char buffer[30] = "ca";
    for (int i = 0; i < 5; i++) { insert_word(root, words[i]); }
    struct Trie *prefix = walk(root, buffer);
    print_words(prefix, buffer, 2); free_trie(root); return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

car
card
care
cat
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Reach the prefix node once, then traverse its descendants in alphabetical child order.
  3. Display the computed result.

Reach the prefix node once, then traverse its descendants in alphabetical child order.

EFFICIENCY

Time and space complexity

Time complexity

O(prefix + output characters)

Auxiliary space

O(total characters * alphabet)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.