Prefix and Suffix Search
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trie.
Prefix and Suffix Search
Design a data structure that allows searching for a word with a given prefix AND a given suffix. If there are multiple valid words, return the largest index.
Visual Representation
Words: ["apple"]
Suffix#Prefix construction: "e#apple", "le#apple", "ple#apple", ...
Insert these into a Trie.
Query: prefix="ap", suffix="le"
Search Trie for "le#ap".
Found node stores max index: 0.Examples
Input: ["WordFilter", "f"]
[[["apple"]], ["a", "e"]]
Output: [null, 0]
Approach 1
Level I: HashMap (All Combinations)
Intuition
Pre-calculate all potential
prefix + '#' + suffix combinations for every word and store them in a HashMap with their index. Query is O(1). Inefficient space but simple.⏱ Pre: O(N * L^2), Query: O(1).💾 O(N * L^2)
Approach 2
Level III: Wrapped Trie ({suffix}#{prefix})
Intuition
To handle both prefix and suffix in a single search, we can insert multiple variations of each word into the Trie. For a word like 'apple', insert: '#apple', 'e#apple', 'le#apple', 'ple#apple', 'pple#apple', 'apple#apple'. A query with prefix 'a' and suffix 'le' becomes a prefix search for 'le#a' in this special Trie.
⏱ Initialization: O(N * L^2), Search: O(L).💾 O(N * L^2).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.