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 pattern array of 0s and 1s
โ€ข An InfiniteStream object with a next() method that reads one bit at a time

Goal: 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
๐Ÿ” Pattern Matching in Infinite Stream๐Ÿ“ก TelegraphIncoming Signal Stream:0110...Target Pattern [1,1,0]:110๐ŸŽฏ Smart Matching Process:1. Use failure function to avoid redundant checks2. On mismatch, jump back intelligently using LPS array
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

n
2n
โœ“ Linear Growth
Space Complexity
O(m)

Space for failure function array of size m (pattern length)

n
2n
โœ“ 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()
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
34.2K Views
Medium Frequency
~25 min Avg. Time
956 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