Prefix and Suffix Search — LeetCode 745 Python Solution
HardDesignTrieArrayHash TableString
- Problem
- #745
- Pattern
- Trie
- Reading time
- 3 min
- Source
- leetcode.com
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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
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
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.