Prefix and Suffix Search
Master this topic with zero to advance depth.
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
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.
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.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.