SDE & MLE Prep

745. Prefix and Suffix Search

Asked at 2Meta24Google5.0

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)