Problem Description
Design an algorithm to process a stream of characters so that upon each new character you can determine whether any suffix of the stream matches one of the words in a given list. Each query returns true if any non-empty suffix of the current stream forms one of the words.
Key Insights
- Instead of checking all possible suffixes against every word, we store words in a Trie data structure.
- Since we are matching suffixes, it is efficient to insert the words in reversed order. This way, when a new character is queried, we traverse the stream backward and the Trie forward.
- Limit the size of the stored stream to the length of the longest word.
- The worst-case query cost is proportional to the maximum length of words.
Space and Time Complexity
Time Complexity: O(M) per query, where M is the maximum length of the words. Space Complexity: O(Total characters in all words) for the Trie plus O(M) for the stream buffer.
Solution
We construct a reverse Trie where each word from the list is stored in reverse order. With every query, append the new character to a stream buffer and traverse this list backwards while matching against the Trie. If at any point you hit a Trie node marked as the end of a word, return true. The stream buffer length is capped at the length of the longest word to ensure efficient memory usage. This method drastically reduces unnecessary comparisons and quickly identifies valid suffixes.