Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Data Structures
Data Structuresmedium

What is a Trie and a common use case?

Tags
#trie#prefix#autocomplete
Back to categoryPractice quiz

Answer

A trie stores strings by prefixes: each node represents a character. It enables fast prefix search/autocomplete; lookup is O(L), where L is the word length.

Advanced answer

Deep dive

A trie (prefix tree) stores keys character-by-character. Each node is a prefix, and a terminal marker indicates a full word. Operations depend on key length L, not on the number of stored keys (aside from memory and cache effects).

Typical operations:

  • insert(word): O(L)
  • search(word): O(L)
  • startsWith(prefix): O(L)

Common use cases

  • Autocomplete / prefix search (type-ahead).
  • Dictionary + spell checking.
  • Routing / IP prefixes (often via compressed tries).

Examples

type Node = { end: boolean; next: Map<string, Node> }
const root: Node = { end: false, next: new Map() }

function insert(word: string) {
  let node = root
  for (const ch of word) {
    const child = node.next.get(ch) ?? { end: false, next: new Map() }
    node.next.set(ch, child)
    node = child
  }
  node.end = true
}

function startsWith(prefix: string): boolean {
  let node = root
  for (const ch of prefix) {
    const child = node.next.get(ch)
    if (!child) return false
    node = child
  }
  return true
}

Trade-offs

  • Tries can be memory-heavy (many nodes). Variants like radix trees/compact tries reduce overhead.
  • Alphabet size matters: arrays are fast for small alphabets; maps save memory for sparse nodes.

Common pitfalls

  • Ignoring Unicode normalization/case-folding (prefixes may not match what users expect).

Related questions

Data Structures
What is a trie and why is it good for prefix search/autocomplete?
#trie#prefix#autocomplete
Data Structures
What is a radix tree (Patricia trie) and when is it better than a normal trie?
#radix-tree#patricia#trie
  • Recursion depth for very long strings (prefer iterative loops).