Prefix and Suffix Search - Problem
You need to design a smart dictionary that can quickly find words based on both their prefix (beginning) and suffix (ending). This is like having a super-powered search engine that can handle queries like "find me all words that start with 'app' and end with 'le'" (which would match 'apple').
Your task is to implement the
โข
โข
If multiple words match the criteria, return the one with the highest index. If no word matches, return
Example: Given words
Your task is to implement the
WordFilter class with two methods:โข
WordFilter(words) - Initialize with an array of dictionary wordsโข
f(prefix, suffix) - Find the word that matches both conditions and return its largest index (most recent occurrence)If multiple words match the criteria, return the one with the highest index. If no word matches, return
-1.Example: Given words
["apple", "application", "app"], searching for prefix="app" and suffix="le" should return index 0 ("apple"). Input & Output
example_1.py โ Basic Usage
$
Input:
WordFilter(["apple"])
f("a", "e")
โบ
Output:
0
๐ก Note:
The word "apple" starts with "a" and ends with "e", so we return its index 0.
example_2.py โ Multiple Matches
$
Input:
WordFilter(["apple", "app", "application"])
f("app", "")
โบ
Output:
2
๐ก Note:
All three words start with "app" and end with empty string, so we return the largest index 2 ("application").
example_3.py โ No Match
$
Input:
WordFilter(["apple", "banana"])
f("app", "na")
โบ
Output:
-1
๐ก Note:
No word starts with "app" AND ends with "na", so we return -1.
Constraints
- 1 โค words.length โค 104
- 1 โค words[i].length โค 7
- 1 โค pref.length, suff.length โค 7
- words[i], pref and suff consist of lowercase English letters only
- At most 104 calls will be made to f
Visualization
Tap to expand
Understanding the Visualization
1
Preprocess Words
For each word like 'apple', create all combinations: 'apple#', 'pple#a', 'ple#ap', 'le#app', 'e#appl', '#apple'
2
Build Trie
Insert all combinations into a trie structure, storing the maximum index at each node
3
Handle Queries
For query f('app', 'le'), search for 'le#app' in the trie
4
Return Result
Return the stored index from trie traversal, or -1 if path doesn't exist
Key Takeaway
๐ฏ Key Insight: Pre-computing all suffix#prefix combinations allows us to answer any prefix-suffix query in O(P+S) time, making this approach optimal for systems with many queries!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code