HardNo. 0745

Prefix and Suffix Search — LeetCode 745 Python Solution

Pattern
Trie
Topics
Design, Trie, Array, Hash Table, String
Reading time
3 min

The problem

Design a special dictionary that searches the words in it by a prefix and a suffix. Implement the WordFilter class: WordFilter(string[] words) Initializes the object with the words in the dictionary.

Example

Input
["WordFilter", "f"]
Output
[null, 0]
Explanation
WordFilter wordFilter = new WordFilter(["apple"]);

Python solution

PythonSolution
class WordFilter:
    def __init__(self, words: List[str]):
        self.d = {}
        for k, w in enumerate(words):
            n = len(w)
            for i in range(n + 1):
                a = w[:i]
                for j in range(n + 1):
                    b = w[j:]
                    self.d[(a, b)] = k

    def f(self, pref: str, suff: str) -> int:
        return self.d.get((pref, suff), -1)


# Your WordFilter object will be instantiated and called as such:
# obj = WordFilter(words)
# param_1 = obj.f(pref,suff)

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 745. Prefix and Suffix Search is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
2227Encrypt and Decrypt StringsHard
0139Word BreakMedium
0140Word Break IIHard
0208Implement Trie (Prefix Tree)Medium
0336Palindrome PairsHard
0648Replace WordsMedium

Frequently asked questions

How hard is LeetCode 745. Prefix and Suffix Search?

LeetCode 745. Prefix and Suffix Search is rated Hard on LeetCode.

What is the time complexity of LeetCode 745. Prefix and Suffix Search?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 745. Prefix and Suffix Search?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 745. Prefix and Suffix Search cover?

LeetCode 745. Prefix and Suffix Search is tagged Design, Trie, Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.