Skip to content

3034. Number of Subarrays That Match a Pattern I 👍

  • Time: $O(|\texttt{nums}| + |\texttt{pattern}|)$
  • Space: $O(|\texttt{nums}| + |\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
54
55
56
57
58
59
60
61
62
class Solution {
 public:
  int countMatchingSubarrays(vector<int>& nums, vector<int>& pattern) {
    const vector<int> numsPattern = getNumsPattern(nums);
    return kmp(numsPattern, pattern);
  }

 private:
  int getNum(int a, int b) {
    if (a < b)
      return 1;
    if (a > b)
      return -1;
    return 0;
  }

  vector<int> getNumsPattern(const vector<int>& nums) {
    vector<int> numsPattern;
    for (int i = 1; i < nums.size(); ++i)
      numsPattern.push_back(getNum(nums[i - 1], nums[i]));
    return numsPattern;
  }

  // Returns the number of occurrences of the pattern in `nums`.
  int kmp(const vector<int>& nums, const vector<int>& pattern) {
    const vector<int> lps = getLPS(pattern);
    int res = 0;
    int i = 0;  // nums' index
    int j = 0;  // pattern's index
    while (i < nums.size()) {
      if (nums[i] == pattern[j]) {
        ++i;
        ++j;
        if (j == pattern.size()) {
          ++res;
          j = lps[j - 1];
        }
      }
      // 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;
      }
    }
    return res;
  }

  // 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
53
54
55
56
57
58
59
60
class Solution {
  public int countMatchingSubarrays(int[] nums, int[] pattern) {
    int[] numsPattern = getNumsPattern(nums);
    return kmp(numsPattern, pattern);
  }

  private int getNum(int a, int b) {
    if (a < b)
      return 1;
    if (a > b)
      return -1;
    return 0;
  }

  private int[] getNumsPattern(int[] nums) {
    int[] numsPattern = new int[nums.length - 1];
    for (int i = 1; i < nums.length; ++i)
      numsPattern[i - 1] = getNum(nums[i - 1], nums[i]);
    return numsPattern;
  }

  // Returns the number of occurrences of the pattern in `nums`.
  private int kmp(int[] nums, int[] pattern) {
    int[] lps = getLPS(pattern);
    int res = 0;
    int i = 0; // nums' index
    int j = 0; // pattern's index
    while (i < nums.length) {
      if (nums[i] == pattern[j]) {
        ++i;
        ++j;
        if (j == pattern.length) {
          ++res;
          j = lps[j - 1];
        }
      }
      // 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;
      }
    }
    return res;
  }

  // Returns the lps array, where lps[i] is the longest proper prefix of
  // pattern[0..i] which is also a suffix of this substring.
  private int[] getLPS(int[] pattern) {
    int[] lps = new int[pattern.length];
    for (int i = 1, j = 0; 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
class Solution:
  def countMatchingSubarrays(self, nums: list[int], pattern: list[int]) -> int:
    def getNum(a: int, b: int) -> int:
      if a < b:
        return 1
      if a > b:
        return -1
      return 0

    numsPattern = [getNum(a, b) for a, b in itertools.pairwise(nums)]
    return self._kmp(numsPattern, pattern)

  def _kmp(self, nums: list[int], pattern: list[int]) -> int:
    """Returns the number of occurrences of the pattern in `nums`."""

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

    lps = getLPS(pattern)
    res = 0
    i = 0  # s' index
    j = 0  # pattern's index
    while i < len(nums):
      if nums[i] == pattern[j]:
        i += 1
        j += 1
        if j == len(pattern):
          res += 1
          j = lps[j - 1]
      # 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
    return res