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 array words.
  • boolean query(char letter) Accepts a new character from the stream and returns true if any non-empty suffix from the stream forms a word that is in words.

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
Stream of Characters: Real-time Suffix DetectionWords Array["cd", "f", "kl"]Character StreamabcdefgMatch Results[F,F,F,T,F,T,F]Suffix "cd" detected at position 3, "f" at position 5Step 1: Store WordsStep 2: Process StreamStep 3: Return Matches🎯 Key Insight: Use reverse trie to match suffixes efficiently in O(L) time per query
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
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
89.2K Views
Medium Frequency
~35 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen