Implement Trie (Prefix Tree)

💡Strategies for Solving This Problem

Understanding Trie (Prefix Tree)

A Trie (pronounced "try") is a tree data structure used for efficient string storage and retrieval. It's particularly powerful for prefix matching, autocomplete, and spell checking.

Why Use a Trie?

Problem: Store dictionary of words, support:

  • Insert word
  • Search for exact word
  • Check if prefix exists

Alternative Approaches:

  • Array/List: Insert O(1), Search O(n*L), Prefix O(n*L)
  • Hash Set: Insert O(L), Search O(L), Prefix O(n*L) - can't do prefix efficiently!
  • Sorted Array + Binary Search: Insert O(n), Search O(log n * L), Prefix O(log n * L + k)
  • Trie: Insert O(L), Search O(L), Prefix O(L) where L = word length ✓

Trie Properties

  • Root represents empty string
  • Each node has up to 26 children (for lowercase a-z)
  • Path from root to node represents a prefix
  • Nodes mark end of word
  • Common prefixes share same path

Example Structure

Dictionary: ["cat", "cats", "dog", "door"]

        root
       /    
      c      d
      |      |
      a      o
      |     / 
      t    g   o
      |        |
      s        r

Marked as end: cat, cats, dog, door

Common Use Cases

  • Autocomplete: Find all words with prefix
  • Spell Checker: Check if word exists, suggest corrections
  • IP Routing: Longest prefix match
  • Dictionary: Word lookup
  • T9 Predictive Text: Phone keyboard suggestions
  • Boggle/Word Search: Fast prefix validation

Time Complexity

  • Insert: O(L) where L = word length
  • Search: O(L)
  • StartsWith: O(L)
  • Space: O(ALPHABET_SIZE * N * L) worst case, much better with shared prefixes

Asked at: Google, Amazon, Microsoft, Facebook, Uber

Scroll to Top