Skip to content

3023. Find Pattern in Infinite Stream I 👍

  • Time: $O(|\texttt{stream}| + |\texttt{pattern}|)$
  • Space: $O(|\texttt{pattern}|)$
 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
/**
 * Definition for an infinite stream.
 * class InfiniteStream {
 *  public:
 *   InfiniteStream(vector<int> bits);
 *   int next();
 * };
 */

class Solution {
 public:
  int findPattern(InfiniteStream* stream, vector<int>& pattern) {
    const vector<int> lps = getLPS(pattern);
    int i = 0;    // stream's index
    int j = 0;    // pattern's index
    int bit = 0;  // the bit in the stream
    bool readNext = false;
    while (true) {
      if (!readNext) {
        bit = stream->next();
        readNext = true;
      }
      if (bit == pattern[j]) {
        ++i, readNext = false;
        ++j;
        if (j == pattern.size())
          return i - j;
      }
      // Mismatch after j matches.
      else if (j > 0) {
        // Don't match lps[0..lps[j - 1]] since they will match anyway.
        j = lps[j - 1];
      } else {
        ++i, readNext = false;
      }
    }
    throw;
  }

 private:
  // Returns the lps array, where lps[i] is the length of the longest prefix of
  // pattern[0..i] which is also a suffix of this substring.
  vector<int> getLPS(const vector<int>& pattern) {
    vector<int> lps(pattern.size());
    for (int i = 1, j = 0; i < pattern.size(); ++i) {
      while (j > 0 && pattern[j] != pattern[i])
        j = lps[j - 1];
      if (pattern[i] == pattern[j])
        lps[i] = ++j;
    }
    return lps;
  }
};
 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
/**
 * Definition for an infinite stream.
 * class InfiniteStream {
 *   public InfiniteStream(int[] bits);
 *   public int next();
 * }
 */

class Solution {
  public int findPattern(InfiniteStream stream, int[] pattern) {
    int[] lps = getLPS(pattern);
    int i = 0;   // stream's index
    int j = 0;   // pattern's index
    int bit = 0; // the bit in the stream
    boolean readNext = false;
    while (true) {
      if (!readNext) {
        bit = stream.next();
        readNext = true;
      }
      if (bit == pattern[j]) {
        ++i;
        readNext = false;
        ++j;
        if (j == pattern.length)
          return i - j;
      }
      // Mismatch after j matches.
      else if (j > 0) {
        // Don't match lps[0..lps[j - 1]] since they will match anyway.
        j = lps[j - 1];
      } else {
        ++i;
        readNext = false;
      }
    }
  }

  // Returns the lps array, where lps[i] is the length of the longest prefix of
  // pattern[0..i] which is also a suffix of this substring.
  private int[] getLPS(int[] pattern) {
    int[] lps = new int[pattern.length];
    int j = 0;
    for (int i = 1; i < pattern.length; ++i) {
      while (j > 0 && pattern[j] != pattern[i])
        j = lps[j - 1];
      if (pattern[i] == pattern[j])
        lps[i] = ++j;
    }
    return lps;
  }
}
 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
# Definition for an infinite stream.
# class InfiniteStream:
#   def next(self) -> int:
#     pass

class Solution:
  def findPattern(
      self,
      stream: Optional['InfiniteStream'],
      pattern: list[int],
  ) -> int:
    lps = self._getLPS(pattern)
    i = 0  # stream's index
    j = 0  # pattern's index
    bit = 0  # the bit in the stream
    readNext = False
    while True:
      if not readNext:
        bit = stream.next()
        readNext = True
      if bit == pattern[j]:
        i += 1
        readNext = False
        j += 1
        if j == len(pattern):
          return i - j
      # Mismatch after j matches.
      elif j > 0:
        # Don't match lps[0..lps[j - 1]] since they will match anyway.
        j = lps[j - 1]
      else:
        i += 1
        readNext = False

  def _getLPS(self, pattern: list[int]) -> list[int]:
    """
    Returns the lps array, where lps[i] is the length of the longest prefix of
    pattern[0..i] which is also a suffix of this substring.
    """
    lps = [0] * len(pattern)
    j = 0
    for i in range(1, len(pattern)):
      while j > 0 and pattern[j] != pattern[i]:
        j = lps[j - 1]
      if pattern[i] == pattern[j]:
        j += 1
        lps[i] = j
    return lps