Practice
longest after processing the input ["a", "app", "ap", "apply"]?Solution
Step 1: Insert words into trie
Words "a", "app", "ap", "apply" are inserted. Only nodes with complete words have word attribute set.Step 2: BFS traversal and update longest
Traversal visits "a" first, then "ap", then "app". "apply" is not valid because "appl" prefix is missing. The longest valid word found is "app".Final Answer:
Option B -> Option BQuick Check:
"app" is longest word with all prefixes present [OK]
- Assuming "apply" is valid without all prefixes
- Not updating longest correctly on equal length
- Skipping lex order in BFS children iteration
Solution
Step 1: Understand the problem constraints
The problem requires checking if any suffix of the stream matches a dictionary word efficiently, which suggests suffix-based matching.Step 2: Evaluate approaches
Brute force checking all suffixes is too slow. Prefix tries do not help with suffix matching. Dynamic programming for all substrings is inefficient. Building a trie of reversed words and traversing it backwards with a limited buffer optimizes both time and space.Final Answer:
Option A -> Option AQuick Check:
Reversed trie + limited buffer matches suffixes efficiently [OK]
- Using prefix trie for suffix matching
- Checking all suffixes brute force
- Using DP on all substrings
Solution
Step 1: Identify the bug in search_shortest_prefix
The function returns prefix after traversing all characters without checking if the current node marks the end of a root word.Step 2: Consequence of missing is_end check
This causes longer prefixes to replace shorter roots, violating the shortest prefix requirement.Final Answer:
Option C -> Option CQuick Check:
Adding is_end check inside loop fixes the bug [OK]
- Returning prefix without is_end check
- Not stopping early at shortest prefix
Solution
Step 1: Identify frequency update location
Frequency must be incremented at each node during insertion to track how many words pass through.Step 2: Locate missing increment
The code does not increment node.freq inside the insertion loop, so frequencies remain zero, causing unique_prefix to fail.Final Answer:
Option C -> Option CQuick Check:
Without freq increments, unique prefix detection breaks [OK]
- Forgetting to increment frequency at each node
- Checking freq before incrementing
Solution
Step 1: Understand '*' wildcard semantics
'*' matches zero or more characters, so search must explore skipping '*' or consuming characters.Step 2: Identify correct search strategy
Using recursion or stack to explore both skipping '*' (index+1) and consuming children (index unchanged) correctly handles zero or more matches.Final Answer:
Option A -> Option AQuick Check:
Branching on both skipping and consuming characters handles '*' wildcard [OK]
- Treating '*' like '.'
- Precomputing expansions is infeasible
- Ignoring '*' wildcard semantics
