DSA
    intermediate

    Trie (Prefix Tree)

    Trie (Prefix Tree)

    Efficient String Storage! Store words by standardizing common prefixes.

    ⏱ O(L)
    💾 O(N*L)
    Ready
    R
    a
    p
    p
    l
    e
    c
    a
    r
    d
    e
    t
    Ready to insert words.
    50%
    Live Variables
    words6
    nodes11

    Insert "cat"

    Sequence

    Order the steps of inserting the word "cat" into a trie.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    21 questions
    Question 1 of 21
    Score: 0

    What is the Time Complexity of searching for a word of length L in a Trie?

    Write the code

    Runs your solution

    Implement Trie

    Implement a Trie with `insert`, `search`, and `startsWith` methods.

    Example Cases

    Input:const t = new Trie(); t.insert("apple"); return t.search("apple");
    Output:true
    Input:const t = new Trie(); t.insert("apple"); return t.search("app");
    Output:false
    Input:const t = new Trie(); t.insert("apple"); return t.startsWith("app");
    Output:true
    javascript

    The short version

    Think of autocomplete on your phone. As you type 'A-P-P', it narrows down the massive dictionary to just the branch containing 'Apple', 'Appetizer', etc. efficient prefix lookup.

    In more depth

    The Prefix Tree

    A Trie (pronounced "try") is a tree-like data structure used for efficiently storing and retrieving keys in a dataset of strings.

    Why use it?

    It excels at prefix-based searches. If you want to find all words starting with "App", a Hash Map can't help you easily, but a Trie can do it in O(L) time where L is the length of the prefix.

    Structure:

    Each node represents a character. Paths from the root to a node represent a string prefix.

    When to reach for this

    • Autocomplete / Typeahead suggestions
    • Spell checker
    • Longest Common Prefix
    • Word Search strategies

    Interview Questions

    Google
    Microsoft
    Google
    Amazon
    Microsoft
    Uber
    Amazon
    Amazon
    Google
    Bloomberg
    Microsoft
    Uber
    Facebook

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required