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
Find Pattern in Infinite Stream I INPUT Pattern to Find: 1 0 pattern = [1, 0] Infinite Stream: 0 i=0 1 i=1 0 i=2 1 i=3 0 i=4 ... Match found! Stream flows forward only stream.next() Returns one bit at a time ALGORITHM STEPS 1 Build KMP Failure Array Preprocess pattern for efficient matching 2 Read Stream Bit by Bit Call next() and track current index position 3 Match with Pattern Compare bit with pattern[j] If mismatch, use KMP jump 4 Return Start Index When j == pattern.length return i - pattern.length + 1 KMP State Machine S0 S1 OK 1 0 FINAL RESULT Pattern Match Found! 0 1 0 1 ... 0 1 2 3 Output: 1 Explanation: Pattern [1,0] first appears starting at index 1 in the stream [0,1,0,1,...] Complexity: Time: O(n + m) Space: O(m) n=stream, m=pattern Key Insight: The KMP (Knuth-Morris-Pratt) algorithm is perfect for this problem because it handles the "no going back" constraint naturally. When a mismatch occurs, instead of restarting from the beginning, KMP uses a precomputed failure array to jump to the optimal position, ensuring each stream bit is read only once. This achieves O(n) time for matching without storing the entire stream in memory! TutorialsPoint - Find Pattern in Infinite Stream I | KMP Optimal Solution
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