Bird
Raised Fist0
Interview PreptriesmediumAmazonGoogleFacebookMicrosoft

Implement Trie (Prefix Tree)

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize Trie with Root Node

Create the root node of the trie, which is empty and has no children or end-of-word flag set.

💡 The root node is the starting point for all insertions and searches; it represents an empty prefix.
Line:class TrieNode: def __init__(self): self.children = {} self.isEnd = False class Trie: def __init__(self): self.root = TrieNode()
💡 The trie starts empty with a single root node ready to build from.
📊
Implement Trie (Prefix Tree) - Watch the Algorithm Execute, Step by Step
Watching each character insertion and traversal helps you understand how tries efficiently store and query strings by sharing prefixes.
Step 1/13
·Active fill★Answer cell
insert
insert
apple
a
insert
apple
ap
insert
apple
app
insert
apple
appl
insert
apple
apple*
search
apple
apple*
search
apple
apple*
Search: true
search
app
apple*
Search: false
startsWith
app
apple*
Search: true
insert
app
apple*
insert
app
app*le*
search
app
app*le*
Search: true

Key Takeaways

✓ Tries efficiently store words by sharing common prefixes, reducing redundant storage.

This is hard to see from code alone because the structure is implicit; visualization shows node sharing clearly.

✓ The isEnd flag on nodes distinguishes between prefixes and complete words.

Without visualization, it's easy to confuse prefix presence with full word presence.

✓ Insertion reuses existing nodes for shared prefixes, creating new nodes only when necessary.

Visualizing each node creation and traversal clarifies how tries grow dynamically.

Practice

(1/5)
1. You are given a list of words and need to find all words that can be formed by concatenating two or more shorter words from the same list. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Trie construction combined with DFS and memoization to efficiently check concatenations
B. Greedy approach that tries to match the longest prefix repeatedly
C. Dynamic programming on substring indices without any prefix tree structure
D. Sorting words by length and checking concatenations using a hash set only

Solution

  1. Step 1: Understand the problem requires checking multiple concatenations efficiently

    Naive substring checks or greedy prefix matches fail to handle overlapping prefixes and repeated subproblems efficiently.
  2. Step 2: Recognize Trie + DFS with memoization optimizes prefix lookups and avoids recomputation

    Trie allows fast prefix matching; DFS explores concatenations; memoization caches results to prevent exponential recomputation.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Trie + DFS + memoization is the known optimal approach [OK]
Hint: Trie + DFS + memoization handles prefix and repeated subproblems efficiently [OK]
Common Mistakes:
  • Assuming greedy prefix matching always works
  • Using DP without prefix optimization
2. Given a string text and a list of words, you need to find all pairs of indices [i, j] such that the substring text[i:j+1] is in the list of words. Which approach guarantees an optimal solution in terms of time complexity when the list of words is large and words have varying lengths?
easy
A. Build a trie from the list of words and perform a DFS from each index in the text to find matching substrings.
B. Use dynamic programming to store whether substrings are in the word list and build results bottom-up.
C. Use a brute force nested loop to check every substring against the list of words directly.
D. Sort the list of words and use binary search to check each substring generated from the text.

Solution

  1. Step 1: Understand the problem constraints

    The problem requires finding all substrings of text that match any word in a large list. Checking every substring against the list directly is expensive.
  2. Step 2: Recognize the trie + DFS pattern

    Building a trie from the words allows prefix-based pruning. DFS from each index in text efficiently finds all matching substrings without redundant checks, guaranteeing optimal time.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Trie + DFS prunes search space better than brute force or binary search [OK]
Hint: Trie + DFS prunes prefix search efficiently [OK]
Common Mistakes:
  • Thinking brute force is efficient enough for large inputs
3. Given a string s and a dictionary of words, you want to determine if s can be segmented into a sequence of dictionary words. Which approach guarantees an optimal solution that efficiently checks prefixes and avoids repeated substring checks?
easy
A. Greedy approach that picks the longest matching prefix at each step
B. Iterative dynamic programming combined with a trie to check prefixes efficiently
C. Pure brute force recursion checking all substring partitions without memoization
D. Sorting the dictionary and using binary search to check substrings

Solution

  1. Step 1: Understand the problem constraints

    The problem requires checking if the string can be segmented into dictionary words, which involves many substring checks.
  2. Step 2: Evaluate approaches for efficiency

    Greedy fails because longest prefix may not lead to a solution; brute force is exponential; binary search is inefficient for substring checks. Using a trie with DP allows prefix checks in O(m) time per position, avoiding repeated substring checks.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Trie + DP efficiently prunes invalid prefixes [OK]
Hint: Trie + DP avoids repeated substring checks [OK]
Common Mistakes:
  • Assuming greedy longest prefix always works
  • Using brute force without memoization
  • Using binary search for substring checks
4. You are given a 2D grid of letters and a list of words. You need to find all words from the list that can be formed by sequentially adjacent letters on the board, where adjacent letters are horizontally or vertically neighboring. Each letter cell may only be used once per word. Which algorithmic approach is best suited to efficiently solve this problem when the word list is large?
easy
A. Build a Trie from the word list and perform a single DFS on the board with prefix pruning using the Trie.
B. Use a brute force DFS for each word independently, checking all paths on the board.
C. Use dynamic programming to store subproblems of partial word matches on the board.
D. Sort the words and use binary search combined with DFS to find matches on the board.

Solution

  1. Step 1: Understand problem constraints and prefix sharing

    Multiple words need to be found on the board, and many words may share prefixes, making prefix pruning beneficial.
  2. Step 2: Use Trie for efficient prefix pruning during DFS

    Building a Trie allows pruning DFS paths early if no word starts with the current prefix, avoiding redundant searches and improving efficiency.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Trie + DFS reduces search space drastically compared to checking each word separately [OK]
Hint: Trie + DFS prunes invalid prefixes early [OK]
Common Mistakes:
  • Thinking brute force DFS per word is efficient
  • Assuming DP applies here
  • Using sorting and binary search without prefix pruning
5. Consider the following buggy code snippet for the longest word in dictionary problem. Which line contains the subtle bug that can cause incorrect results?
medium
A. Line: queue.append(child) without checking if child.word is not None
B. Line: for ch in sorted(node.children.keys())
C. Line: node.word = word in insert method
D. Line: trie.insert(word) in the for loop

Solution

  1. Step 1: Identify enqueue condition

    The BFS queue should only include nodes representing complete words (child.word != None) to ensure all prefixes are valid.
  2. Step 2: Locate the bug

    The code enqueues all children regardless of whether they represent complete words, allowing invalid prefixes to be considered, breaking the prefix condition.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Enqueueing invalid prefix nodes causes incorrect longest word [OK]
Hint: Only enqueue nodes with complete words in BFS [OK]
Common Mistakes:
  • Enqueueing all children regardless of word completion
  • Misplacing word assignment in insert
  • Sorting children incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard