Find Pattern in Infinite Stream II - Problem

You are given a binary array pattern and an object stream of class InfiniteStream representing a 0-indexed infinite stream of bits.

The class InfiniteStream contains the following function:

  • int next(): Reads a single bit (which is either 0 or 1) from the stream and returns it.

Return the first starting index where the pattern matches the bits read from the stream. For example, if the pattern is [1, 0], the first match is the highlighted part in the stream [0, 1, 0, 1, ...].

Note: You can only read each bit from the stream once, and you cannot go back to re-read previous bits.

Input & Output

Example 1 — Basic Pattern Match
$ Input: pattern = [1,0], stream = [0,1,0,1,...]
Output: 1
💡 Note: Pattern [1,0] first appears at index 1 in the stream: [0,1,0,1,...]. The bits at positions 1 and 2 are [1,0].
Example 2 — Pattern at Start
$ Input: pattern = [1,1], stream = [1,1,0,1,1,...]
Output: 0
💡 Note: Pattern [1,1] appears immediately at the beginning of the stream at index 0.
Example 3 — Longer Pattern
$ Input: pattern = [0,0,1], stream = [1,0,0,1,0,0,0,1,...]
Output: 1
💡 Note: Pattern [0,0,1] first appears at index 1: stream positions 1,2,3 contain [0,0,1].

Constraints

  • 1 ≤ pattern.length ≤ 104
  • pattern[i] is either 0 or 1
  • stream consists only of 0s and 1s
  • stream is guaranteed to contain the pattern

Visualization

Tap to expand
Find Pattern [1,0] in Infinite StreamPattern:10Infinite Stream:0101...0123Match!Read stream once, find pattern at index 1Output: 1
Understanding the Visualization
1
Input
Binary pattern and infinite stream of bits
2
Process
Read bits sequentially and match against pattern
3
Output
First index where pattern matches completely
Key Takeaway
🎯 Key Insight: Use KMP or rolling hash to avoid re-reading bits when pattern mismatches occur
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
23.4K Views
Medium Frequency
~25 min Avg. Time
892 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