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].

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()

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.
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