Find Pattern in Infinite Stream I Problem
Description
LeetCode Problem 3023.
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 <= 100patternconsists 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: Bit Manipulation + Sliding Window
The pattern has at most 100 bits, which is too long for one 64-bit integer, so we split it into a left half and a right half. Each half fits into a 64-bit integer: a holds the left half and b holds the right half.
We then read the stream bit by bit and keep the same two numbers, x and y, for the last m bits read (m is the pattern length). A new bit is pushed into y; the bit that falls out of the left end of y moves into x, and bits that fall out of x are dropped. Once at least m bits have been read, we compare x == a and y == b. On a match, the pattern starts at index i - m.
Complexity: time O(n + m), space O(1), where n is the number of bits read and m the pattern length.
from itertools import count
# Definition for an infinite stream.
# class InfiniteStream:
# def next(self) -> int:
# pass
class Solution:
def findPattern(
self, stream: Optional["InfiniteStream"], pattern: List[int]
) -> int:
a = b = 0
m = len(pattern)
half = m >> 1
mask1 = (1 << half) - 1
mask2 = (1 << (m - half)) - 1
for i in range(half):
a |= pattern[i] << (half - 1 - i)
for i in range(half, m):
b |= pattern[i] << (m - 1 - i)
x = y = 0
for i in count(1):
v = stream.next()
y = y << 1 | v
v = y >> (m - half) & 1
y &= mask2
x = x << 1 | v
x &= mask1
if i >= m and a == x and b == y:
return i - m