Stream of Characters - Problem
Stream of Characters is a fascinating real-time pattern matching problem that simulates processing live data streams.
You need to design a data structure that can efficiently detect if any suffix of a character stream matches words from a given dictionary. Think of it like a smart text editor that highlights matching patterns as you type!
Your Task:
- Initialize a
StreamCheckerwith an array of target words - Process characters one by one from a stream
- Return
trueif any suffix of the current stream matches any word in your dictionary
Example: If your dictionary contains ["abc", "xyz"] and you receive characters 'a', 'x', 'y', 'z' in sequence:
- After 'a': stream = "a" → no match → return
false - After 'x': stream = "ax" → no match → return
false - After 'y': stream = "axy" → no match → return
false - After 'z': stream = "axyz" → suffix "xyz" matches! → return
true
The key insight is that you only care about suffixes - you don't need the entire stream to match, just the ending portion.
Input & Output
example_1.py — Basic Example
$
Input:
words = ["cd", "f", "kl"]
Queries: 'a', 'b', 'c', 'd'
›
Output:
false, false, false, true
💡 Note:
Stream builds as: "a" → "ab" → "abc" → "abcd". After 'd', the suffix "cd" matches word "cd" in dictionary.
example_2.py — Multiple Matches
$
Input:
words = ["ab", "ba", "aaab", "abab", "baa"]
Queries: 'a', 'a', 'a', 'b'
›
Output:
false, false, false, true
💡 Note:
Stream: "a" → "aa" → "aaa" → "aaab". After final 'b', suffix "aaab" matches the word "aaab".
example_3.py — Single Character Match
$
Input:
words = ["f"]
Queries: 'x', 'y', 'f'
›
Output:
false, false, true
💡 Note:
Stream: "x" → "xy" → "xyf". After 'f', the suffix "f" matches the single-character word "f".
Visualization
Tap to expand
Understanding the Visualization
1
Setup Scanner
Build reverse lookup system from suspicious patterns
2
Monitor Stream
Keep track of recent visitors in sliding window
3
Pattern Detection
Check if recent visitor sequence matches any pattern
4
Alert System
Trigger alert when suspicious pattern detected
Key Takeaway
🎯 Key Insight: Reverse Trie enables O(k) suffix matching by storing patterns backwards and traversing recent characters in reverse order, making real-time stream processing highly efficient!
Time & Space Complexity
Time Complexity
O(k) per query
k is the maximum word length. We only traverse the trie up to k levels deep
✓ Linear Growth
Space Complexity
O(ALPHABET_SIZE × total_chars_in_all_words)
Space for trie nodes plus O(k) for the sliding window buffer
⚡ Linearithmic Space
Constraints
- 1 ≤ words.length ≤ 2000
- 1 ≤ words[i].length ≤ 200
- words[i] consists of lowercase English letters
- At most 4 × 104 calls will be made to query
- query consists of lowercase English letters
- Memory optimization: Use sliding window to avoid storing entire stream
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code