Prefix and Suffix Search - Problem
Design a special dictionary that searches words by both prefix and suffix. You need to implement the WordFilter class:
WordFilter(string[] words) - Initializes the object with the words in the dictionary.
f(string pref, string suff) - Returns the index of the word in the dictionary that has the prefix pref and the suffix suff. If there are multiple valid indices, return the largest one. If no such word exists, return -1.
Input & Output
Example 1 — Basic Prefix-Suffix Search
$
Input:
words = ["apple", "application", "apply"], queries = [["ap", "e"]]
›
Output:
[0]
💡 Note:
Only 'apple' starts with 'ap' and ends with 'e', so return its index 0
Example 2 — Multiple Matches
$
Input:
words = ["cat", "bat", "rat"], queries = [["a", "t"]]
›
Output:
[-1]
💡 Note:
None of the words start with 'a' and end with 't', so return -1
Example 3 — No Match
$
Input:
words = ["hello", "world"], queries = [["he", "d"]]
›
Output:
[-1]
💡 Note:
No word starts with 'he' and ends with 'd', so return -1
Constraints
- 1 ≤ words.length ≤ 104
- 1 ≤ words[i].length ≤ 7
- 1 ≤ pref.length, suff.length ≤ 7
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code