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 in Infinite Stream II - Rolling Hash INPUT Pattern: [1, 0] 1 0 Infinite Stream: 0 idx:0 1 idx:1 0 idx:2 1 idx:3 ... Match! Constraints: - Read each bit ONCE - Cannot go back - Stream is infinite - Find first match ALGORITHM STEPS 1 Compute Pattern Hash hash_p = 1*2 + 0*1 = 2 2 Read First m Bits Window: [0,1] hash_w = 1 3 Rolling Hash Update Slide window, update hash new_hash = (old_hash - MSB*2^(m-1)) * 2 + new_bit O(1) update per bit 4 Compare Hashes If hash_w == hash_p Window [0,1]: hash=1 != 2 Window [1,0]: hash=2 == 2 OK Return starting index: 1 FINAL RESULT Pattern Found at Index: 1 Stream with match highlighted: 0 1 0 1 ... Pattern [1,0] Complexity Analysis Time: O(n + m) Space: O(m) n=stream, m=pattern len Key Insight: Rolling Hash allows O(1) window hash updates by removing the leftmost bit's contribution and adding the new bit. This avoids recomputing the entire hash for each position, making it efficient for streaming data where we can only read forward. Hash collisions are rare with good base/modulo choices, ensuring correctness. TutorialsPoint - Find Pattern in Infinite Stream II | Rolling Hash Approach
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