746. Prefix and Suffix Search
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to design a WordFilter that can efficiently find a word matching a given prefix and suffix. If multiple words match, we need to return the one with the largest index in the original list. A naive approach would be to iterate through all the words for each query, checking the prefix and suffix. With up to 10,000 words and 10,000 queries, this O(N) per query approach would be too slow.
Solution
Prefix and Suffix Search in Python
class TrieNode:
def __init__(self):
# Children nodes in the Trie.
self.children = {}
# Index of the word. Initialized to -1.
self.index = -1
class WordFilter:
def __init__(self, words: list[str]):
self.trie = TrieNode()
# The separator character should not be in the words.
separator = '{'
for i, word in enumerate(words):
# For each word, generate keys by combining its suffixes with the word itself.
# For example, for "apple", we generate "e{apple", "le{apple", etc.
for j in range(len(word) + 1):
# Suffix part + separator + word part
key = word[j:] + separator + word
# Insert the key into the Trie.
node = self.trie
for char in key:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
# Update the index at each node along the path.
# As we process words with increasing index `i`, this naturally
# finds the largest index for any prefix.
node.index = i
def f(self, pref: str, suff: str) -> int:
# Construct the query key: suffix + separator + prefix.
separator = '{'
query_key = suff + separator + pref
# Search for the query key in the Trie.
node = self.trie
for char in query_key:
if char not in node.children:
return -1
node = node.children[char]
# The index stored at the destination node is the result.
return node.index
# Your WordFilter object will be instantiated and called as such:
# obj = WordFilter(words)
# param_1 = obj.f(pref,suff)
Prefix and Suffix Search in Java
class WordFilter {
class TrieNode {
TrieNode[] children;
int index;
TrieNode() {
// For 'a'-'z' and a special separator '{'.
children = new TrieNode[27];
index = -1;
}
}
private final TrieNode root;
public WordFilter(String[] words) {
root = new TrieNode();
for (int i = 0; i < words.length; i++) {
String word = words[i];
// For each suffix of the word, create a key "suffix{word}" and insert it.
for (int j = 0; j <= word.length(); j++) {
String key = word.substring(j) + "{" + word;
TrieNode curr = root;
for (char c : key.toCharArray()) {
int idx = (c == '{') ? 26 : c - 'a';
if (curr.children[idx] == null) {
curr.children[idx] = new TrieNode();
}
curr = curr.children[idx];
// Update the index at each node on the path.
// Since we iterate words by increasing index, this automatically
// stores the largest index.
curr.index = i;
}
}
}
}
public int f(String pref, String suff) {
// Construct the query key "suff{pref}" and search in the Trie.
String queryKey = suff + "{" + pref;
TrieNode curr = root;
for (char c : queryKey.toCharArray()) {
int idx = (c == '{') ? 26 : c - 'a';
if (curr.children[idx] == null) {
return -1; // Not found.
}
curr = curr.children[idx];
}
// The index at the destination node is the answer.
return curr.index;
}
}
/**
* Your WordFilter object will be instantiated and called as such:
* WordFilter obj = new WordFilter(words);
* int param_1 = obj.f(pref,suff);
*/
Prefix and Suffix Search in C++
class WordFilter {
private:
struct TrieNode {
TrieNode* children[27];
int index;
TrieNode() {
for (int i = 0; i < 27; ++i) {
children[i] = nullptr;
}
index = -1;
}
// Destructor to prevent memory leaks in a real-world scenario.
// Not strictly necessary for LeetCode's execution environment.
~TrieNode() {
for (int i = 0; i < 27; ++i) {
delete children[i];
}
}
};
TrieNode* root;
// Helper to map characters to Trie array index.
// 'a'-'z' -> 0-25, '{' -> 26
int charToIndex(char c) {
return c == '{' ? 26 : c - 'a';
}
public:
WordFilter(vector<string>& words) {
root = new TrieNode();
for (int i = 0; i < words.size(); ++i) {
const string& word = words[i];
const int word_len = word.length();
string key_to_insert = "{" + word;
for (int j = 0; j <= word_len; ++j) {
TrieNode* curr = root;
// Insert suffix part first.
for (int k = j; k < word_len; ++k) {
int idx = charToIndex(word[k]);
if (!curr->children[idx]) {
curr->children[idx] = new TrieNode();
}
curr = curr->children[idx];
curr->index = i;
}
// Then insert the "{word" part.
for (char c : key_to_insert) {
int idx = charToIndex(c);
if (!curr->children[idx]) {
curr->children[idx] = new TrieNode();
}
curr = curr->children[idx];
curr->index = i;
}
}
}
}
int f(string pref, string suff) {
TrieNode* curr = root;
string query_key = suff + "{" + pref;
for (char c : query_key) {
int idx = charToIndex(c);
if (!curr->children[idx]) {
return -1;
}
curr = curr->children[idx];
}
return curr->index;
}
~WordFilter() {
delete root;
}
};
/**
* Your WordFilter object will be instantiated and called as such:
* WordFilter* obj = new WordFilter(words);
* int param_1 = obj->f(pref,suff);
*/
Prefix and Suffix Search in TypeScript
class TrieNode {
children: { [key: string]: TrieNode } = {};
index: number = -1;
}
class WordFilter {
private trie: TrieNode = new TrieNode();
constructor(words: string[]) {
const separator = '{';
for (let i = 0; i < words.length; i++) {
const word = words[i];
// For each suffix of the word, create a key "suffix{word}" and insert it.
for (let j = 0; j <= word.length; j++) {
const key = `${word.substring(j)}${separator}${word}`;
let node = this.trie;
for (const char of key) {
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[char];
// Update the index at each node on the path. Since we iterate
// words by increasing index, this automatically stores the largest index.
node.index = i;
}
}
}
}
f(pref: string, suff: string): number {
const separator = '{';
// Construct the query key "suff{pref}" and search in the Trie.
const queryKey = `${suff}${separator}${pref}`;
let node = this.trie;
for (const char of queryKey) {
if (!node.children[char]) {
return -1; // Not found.
}
node = node.children[char];
}
// The index at the destination node is the answer.
return node.index;
}
}
/**
* Your WordFilter object will be instantiated and called as such:
* var obj = new WordFilter(words)
* var param_1 = obj.f(pref,suff)
*/
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.