Find Pattern in Infinite Stream II - Problem
Pattern Matching in an Infinite Bit Stream
You are given a binary array
Goal: Find the first starting index where the given pattern matches the bits read from the stream.
For example, if
Challenge: Since the stream is infinite and we can only read bits sequentially, we need an efficient algorithm that doesn't require storing the entire stream in memory.
You are given a binary array
pattern and an InfiniteStream object that represents an infinite stream of bits (0s and 1s). The stream provides a single method:int next(): Reads and returns the next bit from the streamGoal: Find the first starting index where the given pattern matches the bits read from the stream.
For example, if
pattern = [1, 0] and the stream contains [0, 1, 0, 1, 0, ...], the first match occurs at index 1 (where we see the subsequence [1, 0]).Challenge: Since the stream is infinite and we can only read bits sequentially, we need an efficient algorithm that doesn't require storing the entire stream in memory.
Input & Output
example_1.py โ Basic Pattern Match
$
Input:
pattern = [1, 0], stream = InfiniteStream([0, 1, 0, 1, 0, ...])
โบ
Output:
1
๐ก Note:
The pattern [1, 0] first appears starting at index 1 in the stream [0, 1, 0, 1, 0, ...]
example_2.py โ Pattern at Beginning
$
Input:
pattern = [1, 1, 0], stream = InfiniteStream([1, 1, 0, 0, 1, 1, 0, ...])
โบ
Output:
0
๐ก Note:
The pattern [1, 1, 0] appears immediately at the start of the stream
example_3.py โ Single Bit Pattern
$
Input:
pattern = [1], stream = InfiniteStream([0, 0, 1, 0, 1, ...])
โบ
Output:
2
๐ก Note:
The first occurrence of bit '1' is at index 2 in the stream
Visualization
Tap to expand
Understanding the Visualization
1
Setup Pattern Hash
Calculate hash value for the target pattern [1,0]
2
Initialize Window
Read first pattern.length bits from stream into sliding window
3
Rolling Hash Check
Compare current window hash with pattern hash
4
Slide Window
Remove oldest bit, add new bit, update hash in O(1)
5
Pattern Found
When hashes match and bits verify, return the starting position
Key Takeaway
๐ฏ Key Insight: Rolling hash allows us to efficiently search infinite streams by updating window hash in O(1) time, avoiding the need to store the entire stream while maintaining optimal performance.
Time & Space Complexity
Time Complexity
O(n + m)
Where n is the number of bits read until match found and m is pattern length. Each bit requires O(1) hash update.
โ Linear Growth
Space Complexity
O(m)
Only store the current window of m bits (pattern length)
โ Linear Space
Constraints
- 1 โค pattern.length โค 104
- pattern[i] is either 0 or 1
- stream.next() returns either 0 or 1
- The stream is guaranteed to contain the pattern
- Memory constraint: Avoid storing the entire infinite stream
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code