3023. Find Pattern in Infinite Stream I π
Description
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
105bits of the stream.
Solutions
Solution 1: Bit Manipulation + Sliding Window
Thinking
The pattern has length at most \(100\) and the stream is unbounded, so we cannot buffer everything. A naive compare at every start can do about \(10^7\) comparisons.
Length \(100\) fits in two \(64\)-bit integers. The stream keeps a sliding window of the same width.
Each new bit shifts the right half; the overflow bit enters the left half. Once the window is full we compare both integers.
We notice that the length of the array \(pattern\) does not exceed \(100\), therefore, we can use two \(64\)-bit integers \(a\) and \(b\) to represent the binary numbers of the left and right halves of \(pattern\).
Next, we traverse the data stream, also maintaining two \(64\)-bit integers \(x\) and \(y\) to represent the binary numbers of the current window of the length of \(pattern\). If the current length reaches the window length, we compare whether \(a\) and \(x\) are equal, and whether \(b\) and \(y\) are equal. If they are, we return the index of the current data stream.
The time complexity is \(O(n + m)\), where \(n\) and \(m\) are the number of elements in the data stream and \(pattern\) respectively. The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |