-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path3023-find-pattern-in-infinite-stream-i.js
More file actions
59 lines (54 loc) · 1.46 KB
/
3023-find-pattern-in-infinite-stream-i.js
File metadata and controls
59 lines (54 loc) · 1.46 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* 3023. Find Pattern in Infinite Stream I
* https://leetcode.com/problems/find-pattern-in-infinite-stream-i/
* Difficulty: Medium
*
* 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, ...].
*/
/**
* Definition for an infinite stream.
* class InfiniteStream {
* @param {number[]} bits
* constructor(bits);
*
* @return {number}
* next();
* }
*/
/**
* @param {InfiniteStream} stream
* @param {number[]} pattern
* @return {number}
*/
var findPattern = function(stream, pattern) {
const patternLength = pattern.length;
const buffer = [];
let currentIndex = 0;
while (buffer.length < patternLength) {
buffer.push(stream.next());
}
while (true) {
if (isPatternMatch(buffer, pattern)) {
return currentIndex;
}
buffer.shift();
buffer.push(stream.next());
currentIndex++;
}
function isPatternMatch(buffer, pattern) {
for (let i = 0; i < pattern.length; i++) {
if (buffer[i] !== pattern[i]) {
return false;
}
}
return true;
}
};