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
Prefix and Suffix Search INPUT words[] array [0] "apple" [1] "application" [2] "apply" Query Prefix "ap" Suffix "e" Find word starting with "ap" AND ending with "e" ALGORITHM STEPS 1 Preprocess Words Generate all prefix+suffix combos 2 Build Hash Map Key: "suff#pref" --> index HashMap for "apple" "e#a" --> 0 "e#ap" --> 0 "le#app" --> 0 "ple#appl" --> 0 "pple#apple" --> 0 ... more combinations "e#ap" --> 0 (match!) 3 Query Lookup Build key: "e" + "#" + "ap" 4 Return Index Get value from map or -1 FINAL RESULT Word Matching "apple" prefix: OK suffix: OK "application" prefix: OK suffix: NO "apply" prefix: OK suffix: NO Output [0] "apple" at index 0 matches both conditions Key Insight: Precompute all possible (suffix + "#" + prefix) combinations for each word and store in a hash map. This trades O(n * L^2) preprocessing time and space for O(1) query time, where L is max word length. For multiple words with same prefix+suffix, later indices overwrite earlier ones (keeping largest index). TutorialsPoint - Prefix and Suffix Search | Hash Map - Preprocess All Combinations
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