Find Pattern in Infinite Stream I - Problem
Find Pattern in Infinite Stream I
You're tasked with finding a specific binary pattern in an infinite stream of bits! ๐
Given:
โข A
โข An
Goal: Return the first starting index where the pattern matches the bits read from the stream.
Example: If pattern =
โ ๏ธ Challenge: You can only read the stream forward - no going back! Once you call
You're tasked with finding a specific binary pattern in an infinite stream of bits! ๐
Given:
โข A
pattern array of 0s and 1sโข An
InfiniteStream object with a next() method that reads one bit at a timeGoal: Return the first starting index where the pattern matches the bits read from the stream.
Example: If pattern =
[1, 0] and the stream produces [0, 1, 0, 1, ...], the first match starts at index 1 (highlighting [1, 0]).โ ๏ธ Challenge: You can only read the stream forward - no going back! Once you call
next(), that bit is consumed. Input & Output
example_1.py โ Basic Pattern Match
$
Input:
pattern = [1, 0], stream = [0, 1, 0, 1, ...]
โบ
Output:
1
๐ก Note:
The pattern [1, 0] first appears at index 1 in the stream [0, 1, 0, 1, ...]. The highlighted match is at positions 1-2.
example_2.py โ Pattern at Start
$
Input:
pattern = [0, 1], stream = [0, 1, 1, 0, ...]
โบ
Output:
0
๐ก Note:
The pattern [0, 1] appears immediately at the start of the stream, so the answer is index 0.
example_3.py โ Repeating Pattern
$
Input:
pattern = [1, 1, 0], stream = [0, 1, 1, 1, 0, ...]
โบ
Output:
2
๐ก Note:
The pattern [1, 1, 0] first matches starting at index 2: stream[2:5] = [1, 1, 0].
Visualization
Tap to expand
Understanding the Visualization
1
Listen to Stream
Receive signals one by one from the telegraph line
2
Smart Matching
Use pattern knowledge to avoid re-checking unnecessary signals
3
Handle Mismatches
When a mismatch occurs, jump back intelligently using the failure function
4
Find Pattern
Return the position when the complete pattern is detected
Key Takeaway
๐ฏ Key Insight: The KMP algorithm's failure function allows us to 'remember' partial matches and avoid redundant comparisons, making pattern matching in streams highly efficient even for complex patterns with repetitive elements.
Time & Space Complexity
Time Complexity
O(n + m)
O(m) to build failure function, O(n) to process stream where n is stream position of first match
โ Linear Growth
Space Complexity
O(m)
Space for failure function array of size m (pattern length)
โ Linear Space
Constraints
- 1 โค pattern.length โค 2000
- pattern[i] is either 0 or 1
- The stream consists of infinite 0s and 1s
- Important: You can only read the stream forward using next()
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code