Find Pattern in Infinite Stream II Problem
Description
LeetCode Problem 3037.
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 either0or1) 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, ...].
Example 1:
Input: stream = [1,1,1,0,1,1,1,...], pattern = [0,1]
Output: 3
Explanation: The first occurrence of the pattern [0,1] is highlighted in the stream [1,1,1,0,1,...], which starts at index 3.
Example 2:
Input: stream = [0,0,0,0,...], pattern = [0]
Output: 0
Explanation: The first occurrence of the pattern [0] is highlighted in the stream [0,...], which starts at index 0.
Example 3:
Input: stream = [1,0,1,1,0,1,1,0,1,...], pattern = [1,1,0,1]
Output: 2
Explanation: The first occurrence of the pattern [1,1,0,1] is highlighted in the stream [1,0,1,1,0,1,...], which starts at index 2.
Constraints:
1 <= pattern.length <= 10^4patternconsists only of0and1.streamconsists only of0and1.- The input is generated such that the pattern's start index exists in the first
10^5bits of the stream.
Solution
Approach: KMP on the Stream
The pattern can have up to 10^4 bits, so the bit-packing idea from the easier version no longer fits. Instead use KMP: the failure table depends only on the pattern, and the matcher never has to move backwards in the stream.
Build the table, then read one bit at a time, keeping k, the length of the longest pattern prefix that ends at the current bit. On a mismatch, fall back with k = fail[k - 1] until the bit fits or k is 0. When k reaches the pattern length after reading bit i, the answer is i - m + 1.
Complexity: time O(n + m) where n is the number of bits read, space O(m).
class Solution:
def findPattern(self, stream: Optional['InfiniteStream'], pattern: List[int]) -> int:
m = len(pattern)
fail = [0] * m
k = 0
for i in range(1, m):
while k and pattern[i] != pattern[k]:
k = fail[k - 1]
if pattern[i] == pattern[k]:
k += 1
fail[i] = k
k = 0
i = 0
while True:
b = stream.next()
while k and b != pattern[k]:
k = fail[k - 1]
if b == pattern[k]:
k += 1
if k == m:
return i - m + 1
i += 1