Prefix and Suffix Search (LeetCode 745): Solution and Explanation
Design a dictionary built from a list of words that answers queries of the form: which word starts with this prefix and ends with this suffix? If several match, return the largest index, and return -1 if none do.
Watch it run step by step
Try your own input and write the code →Intuition
The direct approach scans every word for each query and checks startswith and endswith, keeping the largest index that matches. That is O(N × L) per query, and with up to 10^4 words and 10^4 queries it adds up quickly. The problem is shaped to reward doing work up front in the constructor so that queries are cheap.
The constraints help: each word is at most 7 characters long. A word of length L has only L + 1 prefixes and L + 1 suffixes, so there are at most 64 (prefix, suffix) pairs per word. That is small enough to enumerate every pair and store it. Join each pair into a single key such as prefix + '#' + suffix, where # cannot appear in a word, and map the key to the word's index.
The largest index rule then takes care of itself. Words are processed in order, so if two words produce the same key, the later word simply overwrites the earlier one in the map. A query builds the same kind of key and does one hash lookup. The trade is memory for speed: we store many keys per word, but every query becomes effectively constant time.
Approach: Hash map of all prefix#suffix keys
- In the constructor, loop over the words with their indices.
- For a word of length n, loop
ifrom 0 to n for the prefixword[:i]andjfrom 0 to n for the suffixword[n-j:]. - Store
self.map[word[:i] + '#' + word[n-j:]] = idx. Later words overwrite earlier ones, which keeps the largest index. - In
f(pref, suff), build the keypref + '#' + suff. - Return
self.map.get(key, -1).
Step-by-step example
words = ["apple", "ape"]; queries f("ap", "e"), f("app", "e"), f("b", "")- "apple" at index 0 generates 36 keys, including "ap#e", "app#e", "#" and "apple#apple", each mapped to 0.
- "ape" at index 1 generates 16 keys, including "ap#e" and "#". Those overwrite the earlier entries, so
map["ap#e"] = 1. - f("ap", "e") looks up "ap#e" and returns 1, the larger index of the two matching words.
- f("app", "e") looks up "app#e". Only "apple" generated it, so the answer is 0.
- f("b", "") looks up "b#", which was never generated, so the answer is -1.
Code: Python, Java, C++
1class WordFilter:
2 def __init__(self, words: List[str]):
3 self.map = {}
4 for idx, word in enumerate(words):
5 n = len(word)
6 for i in range(n + 1):
7 for j in range(n + 1):
8 key = word[:i] + '#' + word[n-j:]
9 self.map[key] = idx
10
11 def f(self, pref: str, suff: str) -> int:
12 key = pref + '#' + suff
13 return self.map.get(key, -1)1class WordFilter {
2 Map<String, Integer> map;
3
4 public WordFilter(String[] words) {
5 map = new HashMap<>();
6 for (int idx = 0; idx < words.length; idx++) {
7 String word = words[idx];
8 int n = word.length();
9 for (int i = 0; i <= n; i++) {
10 for (int j = 0; j <= n; j++) {
11 String key = word.substring(0, i) + "#" + word.substring(n - j);
12 map.put(key, idx);
13 }
14 }
15 }
16 }
17
18 public int f(String pref, String suff) {
19 String key = pref + "#" + suff;
20 return map.getOrDefault(key, -1);
21 }
22}1class WordFilter {
2 unordered_map<string, int> mp;
3public:
4 WordFilter(vector<string>& words) {
5 for (int idx = 0; idx < words.size(); idx++) {
6 string& word = words[idx];
7 int n = word.size();
8 for (int i = 0; i <= n; i++) {
9 for (int j = 0; j <= n; j++) {
10 string key = word.substr(0, i) + "#" + word.substr(n - j);
11 mp[key] = idx;
12 }
13 }
14 }
15 }
16
17 int f(string pref, string suff) {
18 string key = pref + "#" + suff;
19 return mp.count(key) ? mp[key] : -1;
20 }
21};Time and space complexity
O(N × L³) to build, O(p + s) per query
Each of the N words creates (L + 1)² keys of length up to 2L + 1, so building costs O(N × L³). A query builds one key from the prefix and suffix and hashes it.
O(N × L³)
The map can hold (L + 1)² keys per word, each of length O(L). With L at most 7 that is a manageable constant per word.
Other approaches
Trie of suffix#word strings (time O(N × L²) to build, O(p + s) per query, space O(N × L²))
For each word, insert suffix + '#' + word into a trie for every suffix, and store the latest index at every node along the way. A query walks suff + '#' + pref and returns the index at the final node. It shares prefixes between keys and is the classic interview answer when memory matters.
Scan all words per query (time O(N × L) per query, space O(1))
Walk the words from the last index backward and return the first that matches both prefix and suffix. It needs no preprocessing and is fine for a handful of queries.
Common mistakes
- Forgetting the empty prefix and empty suffix, which come from
i = 0andj = 0. Queries are allowed to use them. - Joining prefix and suffix without a separator, so "ab" + "c" and "a" + "bc" produce the same key.
- Writing
word[-j:]for the suffix, which returns the whole word whenjis 0 instead of an empty string. - Keeping the first index seen for a key instead of the last, which violates the largest index rule.
Frequently asked questions
Why is precomputing all pairs acceptable here?
Words are at most 7 characters, so each word has at most 64 prefix and suffix combinations. That keeps the map size bounded while making every query a single lookup.
How does the trie solution work for Prefix and Suffix Search?
Each suffix of a word is joined with a separator and the full word, then inserted into one trie. Searching for suffix#prefix then follows a single path, and each node stores the largest index that passed through it.
How do duplicate words affect the answer?
Processing words in order and overwriting map entries means a repeated word's keys end up pointing at its last occurrence, which is the largest index as the problem requires.
What if words could be much longer?
The number of keys grows with the square of word length, so for long words the map would get too large. In that case two tries (one for prefixes, one for reversed suffixes) whose nodes store sorted index lists, intersected at query time, scale better.