Stream of Characters - Problem
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string from a given array of strings words.
For example, if words = ["abc", "xyz"] and the stream added the four characters (one by one) 'a', 'x', 'y', and 'z', your algorithm should detect that the suffix "xyz" of the characters "axyz" matches "xyz" from words.
Implement the StreamChecker class:
StreamChecker(String[] words)Initializes the object with the strings arraywords.boolean query(char letter)Accepts a new character from the stream and returnstrueif any non-empty suffix from the stream forms a word that is inwords.
Input & Output
Example 1 — Basic Stream Processing
$
Input:
words = ["cd", "f", "kl"], queries = "abcdefg"
›
Output:
[false, false, false, true, false, true, false]
💡 Note:
Stream builds as 'a', 'ab', 'abc', 'abcd' (suffix 'cd' matches), 'abcde', 'abcdef' (suffix 'f' matches), 'abcdefg'
Example 2 — Multiple Matches
$
Input:
words = ["ab", "ba", "aaab"], queries = "aaba"
›
Output:
[false, false, true, true]
💡 Note:
Stream: 'a' → 'aa' → 'aab' (suffix 'ab' matches) → 'aaba' (suffix 'ba' matches)
Example 3 — No Matches
$
Input:
words = ["xyz"], queries = "abc"
›
Output:
[false, false, false]
💡 Note:
Stream 'a' → 'ab' → 'abc' never forms suffix 'xyz'
Constraints
- 1 ≤ words.length ≤ 2000
- 1 ≤ words[i].length ≤ 2000
- words[i] consists of lowercase English letters
- At most 4 × 104 calls to query
Visualization
Tap to expand
Understanding the Visualization
1
Input
Words array ["cd", "f"] and character stream
2
Process
Build data structure and process each character
3
Output
Boolean array indicating suffix matches
Key Takeaway
🎯 Key Insight: Reverse trie enables O(L) suffix matching per character instead of O(n²) brute force
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code