745. Prefix and Suffix Search
Problem
Design WordFilter(words) whose f(pref, suff) returns the largest index of a word that starts with pref and ends with suff, or −1 if there is none.
Example: WordFilter(["apple"]) → f("a","e") = 0
Constraints: up to 10⁴ words of length ≤ 7; up to 10⁴ calls to f.
Words are short (≤ 7 chars), so precompute every (prefix, suffix) combination per word into a map prefix + "#" + suffix → index (later words overwrite → largest index wins). Queries become O(1). Trie alternative: insert suffix + "#" + word for every suffix and store the max index at each node.
Complexity: O(N · L²) build (L³ including string copies), O(L) query.
class WordFilter:
def __init__(self, words: List[str]):
self.idx = {}
for i, w in enumerate(words):
for p in range(len(w) + 1):
for s in range(len(w) + 1):
self.idx[w[:p] + "#" + w[s:]] = i
def f(self, pref: str, suff: str) -> int:
return self.idx.get(pref + "#" + suff, -1)
wf = WordFilter(["apple", "ape", "maple"])
assert wf.f("a", "e") == 1 and wf.f("ap", "le") == 0 and wf.f("", "le") == 2 and wf.f("b", "") == -1
assert WordFilter(["apple"]).f("a", "e") == 0
assert WordFilter(["abc", "abc"]).f("a", "c") == 1
class WordFilter {
private final Map<String, Integer> idx = new HashMap<>();
public WordFilter(String[] words) {
for (int i = 0; i < words.length; i++) {
String w = words[i];
for (int p = 0; p <= w.length(); p++)
for (int s = 0; s <= w.length(); s++) idx.put(w.substring(0, p) + "#" + w.substring(s), i);
}
}
public int f(String pref, String suff) { return idx.getOrDefault(pref + "#" + suff, -1); }
}
type WordFilter struct {
idx map[string]int // "prefix#suffix" -> largest index
}
func Constructor(words []string) WordFilter {
idx := map[string]int{}
for i, w := range words {
for p := 0; p <= len(w); p++ {
for s := 0; s <= len(w); s++ {
idx[w[:p]+"#"+w[s:]] = i // later words overwrite earlier ones
}
}
}
return WordFilter{idx}
}
func (this *WordFilter) F(pref string, suff string) int {
if i, ok := this.idx[pref+"#"+suff]; ok {
return i
}
return -1
}