Reverse Trie for Ending Pattern Queries
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests understanding of tries and the insight that suffix matching becomes prefix matching when strings are reversed.
Reverse Trie for Ending Pattern Queries
Build a data structure that stores strings and efficiently answers whether any stored string ends with a given pattern.
Your structure must support two operations:
- Adding a new string to the collection
- Checking if any string in the collection ends with a specific pattern
Both operations should run in time proportional to the length of the input string or pattern.
Implement the EndingMatcher class:
EndingMatcher(): Creates an empty matcher.void add_word(str word): Addswordto the collection.bool matches_ending(str pattern): Returnstrueif at least one word in the collection ends withpattern, otherwise returnsfalse.
Constraints
1 <= word.length, pattern.length <= 2,000- All strings contain only printable ASCII characters
- Matching is case-sensitive
- At most
100,000operations total - Total characters across all added words does not exceed
1,000,000
Behavior Notes
- A word matches its own ending (adding
"hello"meansmatches_ending("hello")returnstrue) - Querying an empty collection returns
false - Case matters:
"Test"and"test"are different patterns - Words can be added multiple times (duplicates are allowed but don't change query results)
Examples
Example 1
Input: run_suffix_index(['insert', 'insert', 'insert', 'has_suffix', 'has_suffix', 'has_suffix', 'has_suffix', 'has_suffix'], [['surveillance'], ['guidance'], ['reconnaissance'], ['ance'], ['lance'], ['surveil'], ['e'], ['drone']])
Output: [None, None, None, True, True, False, True, False]
Example 2
Input: run_suffix_index(['has_suffix', 'insert', 'has_suffix', 'insert', 'has_suffix', 'has_suffix'], [['x'], ['x'], ['x'], ['Radar'], ['radar'], ['Radar']])
Output: [False, None, True, None, False, True]
Example 3
Input: run_suffix_index(['insert', 'insert', 'has_suffix', 'has_suffix', 'has_suffix'], [['target'], ['market'], ['target'], ['ket'], ['tar']])
Output: [None, None, True, True, False]
Hints
Hint 1
Think about how prefix matching works with tries. Can you transform suffix matching into prefix matching?
Hint 2
If you reverse a word, its suffix becomes a prefix of the reversed word.
Hint 3
Store reversed words in a trie. Then checking for a suffix becomes checking if the reversed pattern exists as a prefix in your trie.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is recognizing that suffix matching can be transformed into prefix matching by reversing strings. A word ends with a pattern if and only if the reversed word starts with the reversed pattern.
We use a trie (prefix tree) structure, but store words in reverse:
-
Adding a word: Traverse the word backward (last character to first), creating trie nodes as we go. Each character becomes a child node.
-
Checking a pattern: Traverse the pattern backward through the trie. If we can follow the entire path, then at least one word ends with this pattern. If any character is missing, no word has this ending.
Unlike standard trie word lookup, we don't need end-of-word markers. Any path that exists in our trie was created by some added word. If the reversed pattern path exists, it means some word's reversal starts with it, which means that word ends with the pattern.
Why this works:
When we add "guidance", we create the path e → c → n → a → d → i → u → g. Any prefix of this path corresponds to a suffix of the original word. The path e → c → n → a exists, so "ance" is a valid ending. The path e → c → n → a → l doesn't exist completely (no l child under a), so "lance" doesn't match.
Words sharing common endings share trie nodes. After adding "guidance" and "reconnaissance", both share the path e → c → n → a because both end with "ance".
Complexity
Time Complexity:
add_word(word): O(L) where L is the length of the word. We visit each character once.matches_ending(pattern): O(P) where P is the length of the pattern. We traverse at most P nodes, stopping early if we hit a missing edge.- Overall: O(total characters processed), bounded by 1,000,000 for insertions plus query costs.
Space Complexity:
- O(N) where N is the total length of all added words. In the best case (many shared endings), space is less. In the worst case (all unique endings), we store roughly one node per character.
Note: A hash-set approach storing all possible suffixes would require O(L²) time and space per word, making it impractical for large inputs.
Solution
from typing import List, Optional
class EndingMatcher:
def __init__(self):
self.root = {}
def add_word(self, word: str) -> None:
node = self.root
for char in reversed(word):
node = node.setdefault(char, {})
def matches_ending(self, pattern: str) -> bool:
node = self.root
for char in reversed(pattern):
if char not in node:
return False
node = node[char]
return True
def run_suffix_index(operations: List[str], arguments: List[List[str]]) -> List[Optional[bool]]:
matcher = EndingMatcher()
results = []
for op, args in zip(operations, arguments):
if op == "insert":
matcher.add_word(args[0])
results.append(None)
elif op == "has_suffix":
results.append(matcher.matches_ending(args[0]))
return results