Bird
Raised Fist0
Interview PreptriesmediumGoogleAmazon

Longest Word in Dictionary

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize Trie and Root Node

Create an empty trie with a root node that has no children and does not mark the end of any word.

💡 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.word = None class Trie: def __init__(self): self.root = TrieNode()
💡 The trie starts empty, ready to build from the root.
📊
Longest Word in Dictionary - Watch the Algorithm Execute, Step by Step
Watching the trie construction and BFS traversal visually reveals how the algorithm ensures all prefixes exist before considering a word, which is hard to grasp from code alone.
Step 1/13
·Active fill★Answer cell
insert
insert
w
w*
insert
wo
w*o*
insert
wor
w*o*r*
insert
worl
w*o*r*l*
insert
world
w*o*r*l*d*
search
w*o*r*l*d*
search
w
w*o*r*l*d*
search
wo
w*o*r*l*d*
search
wor
w*o*r*l*d*
search
worl
w*o*r*l*d*
search
world
w*o*r*l*d*
search
world
w*o*r*l*d*
Search: true

Key Takeaways

✓ The trie structure efficiently shares prefixes among words, reducing redundant storage.

This is hard to see from code alone because the sharing happens implicitly in the data structure.

✓ BFS traversal only enqueues nodes that mark complete words, ensuring all prefixes exist for candidate words.

This filtering step is crucial and not obvious without visualizing the traversal.

✓ The longest word is updated dynamically during BFS, reflecting the lexicographically smallest word when lengths tie.

Understanding this tie-breaking rule is easier when watching the word updates step-by-step.

Practice

(1/5)
1. 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
2. Consider the following Python code implementing the trie + DFS approach to find index pairs of substrings matching words. Given text = "abcab" and words = ["ab", "bc", "ca"], what is the final sorted list res returned by indexPairs(text, words)?
easy
A. [[0,1],[1,2],[3,4]]
B. [[0,1],[1,2],[2,3]]
C. [[0,1],[2,3],[3,4]]
D. [[0,1],[1,2],[2,3],[3,4]]

Solution

  1. Step 1: Build the trie from words ["ab", "bc", "ca"]

    The trie has branches for 'a'->'b', 'b'->'c', and 'c'->'a', each marking word_end at the last character.
  2. Step 2: DFS from each index in text "abcab"

    From index 0: 'a'->'b' matches "ab" -> [0,1]. From index 1: 'b'->'c' matches "bc" -> [1,2]. From index 2: 'c'->'a' matches "ca" -> [2,3]. From index 3: 'a'->'b' matches "ab" -> [3,4]. From index 4: 'b' no further match.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    All four pairs found and sorted correctly [OK]
Hint: Trace DFS from each index carefully [OK]
Common Mistakes:
  • Missing last match at index 3
  • Off-by-one in end index
3. Consider the following buggy insert method for MapSum. Which line contains the subtle bug that causes incorrect sum queries after updating an existing key's value?
medium
A. Line where root node sum update is commented out
B. Line where delta is computed
C. Line where map[key] is updated
D. Line where child node sum is updated

Solution

  1. Step 1: Understand delta and map update

    Delta correctly computes difference; map updated correctly.
  2. Step 2: Identify missing root sum update

    Root node sum update is commented out, so total sums are stale, causing incorrect sum queries.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Root sum must be updated to keep prefix sums accurate [OK]
Hint: Root sum update is critical for correct prefix sums [OK]
Common Mistakes:
  • Forgetting root sum update
  • Updating map incorrectly
  • Misplacing child sum updates
4. Examine the following buggy code snippet for building the trie and collecting suggestions. Which line contains the subtle bug that can cause incorrect suggestion ordering or runtime errors?
medium
A. Line with 'products.sort()' missing before building trie
B. Line with 'for product in products:' loop
C. Line with 'if len(node.suggestions) < 3:' condition
D. Line with 'if node and ch in node.children:' during search

Solution

  1. Step 1: Identify missing sorting

    The code does not sort products before building the trie, so suggestions are appended in input order, not lex order.
  2. Step 2: Consequences of missing sort

    Without sorting, the suggestions list at each node is not guaranteed to be lexicographically smallest three, violating problem requirements.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sorting before trie build is essential for correct lex order [OK]
Hint: Always sort products before building trie for lex order [OK]
Common Mistakes:
  • Forgetting to sort products
  • Appending suggestions without limit
  • Not handling missing prefix nodes
5. Suppose the problem is modified so that pairs can be counted multiple times if elements are reused (i.e., pairs (i, j) with i and j possibly equal). Which modification to the bitwise trie approach correctly handles this scenario?
hard
A. Modify the query function to include the current number in the trie before querying to count pairs with itself.
B. No change needed; the existing approach already counts pairs with reuse.
C. Insert all numbers into the trie first, then for each number query the trie for counts less than limit, allowing reuse.
D. Use a frequency map instead of a trie since reuse breaks trie assumptions.

Solution

  1. Step 1: Understand reuse means pairs can include the same element twice

    Counting pairs with i == j means the current number must be considered in queries.
  2. Step 2: Modify insertion and query order

    Insert the current number into the trie before querying so it can pair with itself and others, enabling reuse counting.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Inserting before querying allows counting pairs including the current element [OK]
Hint: Insert before query to count pairs with reuse [OK]
Common Mistakes:
  • Assuming no change needed
  • Inserting after query (misses self pairs)
  • Switching to frequency map unnecessarily
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