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: [2]
💡 Note: Both 'cat' and 'rat' start with 'a' and end with 't', but we return the largest index 2
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
Prefix and Suffix Search: Find words matching both conditionsDictionary['apple', 'application', 'apply']Queryprefix='ap', suffix='e'Check Wordsapple: ap...e ✓application: ap...n ✗apply: ap...y ✗Only 'apple' matches both conditionsResult: 0
Understanding the Visualization
1
Input
Dictionary: ['apple', 'application', 'apply'] | Query: prefix='ap', suffix='e'
2
Process
Check each word: does it start with 'ap' AND end with 'e'?
3
Output
Return index of matching word (largest if multiple matches)
Key Takeaway
🎯 Key Insight: Preprocess all prefix-suffix combinations for O(1) lookup time
Asked in
Google 25 Amazon 18 Microsoft 12
28.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen