Tutorials Logic, IN info@tutorialslogic.com

Trie Data Structure Insert, Search, Autocomplete: Tutorial, Examples, FAQs & Interview Tips

Trie Data Structure Insert, Search, Autocomplete

Trie is a practical Data Structure topic that becomes clear when you connect the definition to a small working example.

Use this page to understand what happens, why it happens, how to verify it, and what mistake usually breaks the concept.

After reading, practice Trie with a normal case, a boundary case, and a broken case so the idea becomes usable instead of memorized.

Trie Data Structure Insert Search Autocomplete should be studied as a practical Data Structure lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the data-structure > trie page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

What is a Trie?

A Trie (pronounced "try", from retrieval) is a tree-like data structure used to store strings where each node represents a character. It is optimized for prefix-based searches - finding all words with a given prefix is O(prefix length), not O(n x word length).

Use cases: Autocomplete, spell checkers, IP routing, dictionary implementations, word games.

  • Insert - O(m) where m = word length
  • Search - O(m)
  • Prefix search - O(m)
  • Space - O(ALPHABET_SIZE x m x n) - can be large

Trie - Insert, Search, StartsWith, Autocomplete

Trie - Insert, Search, StartsWith, Autocomplete
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

struct TrieNode {
    unordered_map<char, TrieNode*> children;
    bool isEnd = false;
};

class Trie {
    TrieNode* root;
public:
    Trie() { root = new TrieNode(); }

    void insert(const string& word) {
        TrieNode* node = root;
        for (char c : word) {
            if (!node->children.count(c))
                node->children[c] = new TrieNode();
            node = node->children[c];
        }
        node->isEnd = true;
    }

    bool search(const string& word) {
        TrieNode* node = root;
        for (char c : word) {
            if (!node->children.count(c)) return false;
            node = node->children[c];
        }
        return node->isEnd;
    }

    bool startsWith(const string& prefix) {
        TrieNode* node = root;
        for (char c : prefix) {
            if (!node->children.count(c)) return false;
            node = node->children[c];
        }
        return true;
    }

    // Autocomplete: find all words with given prefix
    void collectWords(TrieNode* node, string current, vector<string>& results) {
        if (node->isEnd) results.push_back(current);
        for (auto& [c, child] : node->children)
            collectWords(child, current + c, results);
    }

    vector<string> autocomplete(const string& prefix) {
        TrieNode* node = root;
        for (char c : prefix) {
            if (!node->children.count(c)) return {};
            node = node->children[c];
        }
        vector<string> results;
        collectWords(node, prefix, results);
        return results;
    }
};

int main() {
    Trie trie;
    for (const string& w : {"apple","app","application","apply","apt","banana"})
        trie.insert(w);

    cout << boolalpha;
    cout << trie.search("app")    << endl;  // true
    cout << trie.search("ap")     << endl;  // false
    cout << trie.startsWith("app") << endl; // true

    auto words = trie.autocomplete("app");
    cout << "Words with 'app': ";
    for (const string& w : words) cout << w << " ";
    cout << endl;  // app apple application apply
    return 0;
}

What is a Trie?

What is a Trie?
import java.util.*;

public class Trie {
    static class TrieNode {
        Map<Character, TrieNode> children = new HashMap<>();
        boolean isEnd = false;
    }

    TrieNode root = new TrieNode();

    void insert(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            node.children.putIfAbsent(c, new TrieNode());
            node = node.children.get(c);
        }
        node.isEnd = true;
    }

    boolean search(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            if (!node.children.containsKey(c)) return false;
            node = node.children.get(c);
        }
        return node.isEnd;
    }

    boolean startsWith(String prefix) {
        TrieNode node = root;
        for (char c : prefix.toCharArray()) {
            if (!node.children.containsKey(c)) return false;
            node = node.children.get(c);
        }
        return true;
    }

    List<String> autocomplete(String prefix) {
        TrieNode node = root;
        for (char c : prefix.toCharArray()) {
            if (!node.children.containsKey(c)) return new ArrayList<>();
            node = node.children.get(c);
        }
        List<String> results = new ArrayList<>();
        collectWords(node, new StringBuilder(prefix), results);
        return results;
    }

    void collectWords(TrieNode node, StringBuilder current, List<String> results) {
        if (node.isEnd) results.add(current.toString());
        for (Map.Entry<Character, TrieNode> e : node.children.entrySet()) {
            current.append(e.getKey());
            collectWords(e.getValue(), current, results);
            current.deleteCharAt(current.length() - 1);
        }
    }

    public static void main(String[] args) {
        Trie trie = new Trie();
        for (String w : new String[]{"apple","app","application","apply","banana"})
            trie.insert(w);
        System.out.println(trie.search("app"));      // true
        System.out.println(trie.startsWith("app"));  // true
        System.out.println(trie.autocomplete("app")); // [app, apple, application, apply]
    }
}

What is a Trie?

What is a Trie?
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end = False

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

    def insert(self, word):
        node = self.root
        for c in word:
            if c not in node.children:
                node.children[c] = TrieNode()
            node = node.children[c]
        node.is_end = True

    def search(self, word):
        node = self.root
        for c in word:
            if c not in node.children: return False
            node = node.children[c]
        return node.is_end

    def starts_with(self, prefix):
        node = self.root
        for c in prefix:
            if c not in node.children: return False
            node = node.children[c]
        return True

    def autocomplete(self, prefix):
        node = self.root
        for c in prefix:
            if c not in node.children: return []
            node = node.children[c]
        results = []
        self._collect(node, prefix, results)
        return results

    def _collect(self, node, current, results):
        if node.is_end: results.append(current)
        for c, child in node.children.items():
            self._collect(child, current + c, results)

trie = Trie()
for w in ["apple", "app", "application", "apply", "banana"]:
    trie.insert(w)

print(trie.search("app"))        # True
print(trie.search("ap"))         # False
print(trie.starts_with("app"))   # True
print(trie.autocomplete("app"))  # ['app', 'apple', 'application', 'apply']

What is a Trie?

What is a Trie?
class TrieNode {
    constructor() { this.children = {}; this.isEnd = false; }
}

class Trie {
    constructor() { this.root = new TrieNode(); }

    insert(word) {
        let node = this.root;
        for (const c of word) {
            if (!node.children[c]) node.children[c] = new TrieNode();
            node = node.children[c];
        }
        node.isEnd = true;
    }

    search(word) {
        let node = this.root;
        for (const c of word) {
            if (!node.children[c]) return false;
            node = node.children[c];
        }
        return node.isEnd;
    }

    startsWith(prefix) {
        let node = this.root;
        for (const c of prefix) {
            if (!node.children[c]) return false;
            node = node.children[c];
        }
        return true;
    }

    autocomplete(prefix) {
        let node = this.root;
        for (const c of prefix) {
            if (!node.children[c]) return [];
            node = node.children[c];
        }
        const results = [];
        this._collect(node, prefix, results);
        return results;
    }

    _collect(node, current, results) {
        if (node.isEnd) results.push(current);
        for (const [c, child] of Object.entries(node.children)) {
            this._collect(child, current + c, results);
        }
    }
}

const trie = new Trie();
["apple","app","application","apply","banana"].forEach(w => trie.insert(w));
console.log(trie.search("app"));        // true
console.log(trie.startsWith("app"));    // true
console.log(trie.autocomplete("app"));  // ['app', 'apple', 'application', 'apply']

Deep Study Notes for Trie

Trie should be learned as a practical Data Structure skill, not only as a definition. Start by asking what problem the topic solves, what input or state it receives, what rule it applies, and what visible result proves it worked.

A strong explanation of Trie includes the normal case, a boundary case, and a failure case. When you practice, write down the before-state, the operation, the after-state, and the reason the result changed.

This lesson was expanded because the audit reported: fewer than 2 sections; limited checklist/practice/mistake/FAQ notes . The added notes below focus on clearer explanation, more examples, and concrete practice so the topic is easier to understand from the page itself.

  • Define the exact problem solved by Trie before looking at syntax.
  • Trace one small example by hand and describe every step in plain language.
  • Identify what changes when the input is empty, repeated, invalid, delayed, or larger than expected.
  • Connect the topic to a realistic project scenario instead of treating it as isolated theory.
  • Verify your answer with output, logs, query results, browser behavior, compiler feedback, or a state table.

Worked Explanation: Using Trie Correctly

Imagine you are adding Trie to a small learning project. The first step is to choose the smallest scenario that still shows the main idea. Avoid starting with a large production design; it hides the concept behind too many details.

Next, isolate the moving parts. Name the input, the rule, the output, and the possible error. This habit makes the topic easier to debug because you can see whether the problem is caused by bad data, wrong configuration, incorrect syntax, timing, permissions, or misunderstanding of the rule.

Finally, compare two versions: one correct version and one intentionally broken version. The broken version is valuable because it teaches you how the topic fails in real work, which is usually what interviews and debugging tasks test.

  • Normal case: show the expected behavior with simple, valid input.
  • Boundary case: test the smallest, largest, empty, repeated, or unusual value that still belongs to the topic.
  • Failure case: introduce one realistic mistake and explain the symptom it creates.
  • Repair step: change one thing at a time so you know exactly what fixed the problem.

Trie trace helper

Trie trace helper
def trace_trie(items):
    print('Input:', items)
    for index, value in enumerate(items):
        print(f'step={index}, value={value}, remaining={items[index+1:]}')
    return len(items)

print('operations:', trace_trie([4, 1, 7, 1]))

Trie edge-case practice

Trie edge-case practice
test_cases = [[], [5], [3, 3, 3], [9, -1, 0, 9]]
for case in test_cases:
    print('case:', case, 'size:', len(case))

# Explain the behavior for empty, single, repeated, and mixed data before optimizing.
Key Takeaways
  • State the purpose of Trie in one sentence before using it.
  • Create a tiny Data Structure example that demonstrates the topic without unrelated code.
  • Test one normal input, one edge input, and one incorrect input for Trie.
  • Explain the result using before-state, operation, and after-state.
  • Add a verification step such as output, logs, query results, browser behavior, or compiler feedback.
Common Mistakes to Avoid
WRONG Memorizing Trie as a definition only.
RIGHT Pair the definition with a small working example and a failure example.
The fastest way to remember the topic is to explain why the output changes.
WRONG Copying syntax without checking the state before and after.
RIGHT Write the input state, apply the rule, then inspect the output state.
State tracing turns confusing behavior into a visible sequence.
WRONG Ignoring the error path for Trie.
RIGHT Create one intentionally broken version and document the symptom and fix.
A page is much easier to learn from when it explains both success and failure.
WRONG Memorizing Trie Data Structure Insert Search Autocomplete without the situation where it is useful.
RIGHT Connect Trie Data Structure Insert Search Autocomplete to a concrete Data Structure task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Build the smallest working demo for Trie and write what each line does.
  • Change one input or setting and predict the result before running it.
  • Break the example in a realistic way, then fix it and describe the repair.
  • Create a two-column note comparing when to use Trie and when another approach is better.
  • Explain Trie aloud as if teaching a beginner who knows basic Data Structure only.

Frequently Asked Questions

Understand the problem it solves, the input or state it works on, and the visible result that proves the concept is working.

Use one tiny correct example, one boundary example, and one broken example. Compare the output or state after each change.

They often memorize the term without tracing the behavior. Tracing makes the rule easier to remember and debug.

Remember the problem it solves in Data Structure, then attach the syntax or steps to that problem.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.