Input: nums =[1,2,3,4,5,6], pattern =[1,1]Output: 4Explanation: The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3],[2,3,4],[3,4,5], and [4,5,6] match this pattern.Hence, there are 4 subarrays in nums that match the pattern.
Input: nums =[1,4,4,1,3,5,5,3], pattern =[1,0,-1]Output: 2Explanation: Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.Hence, there are 2 subarrays in nums that match the pattern.
We need to count the number of subarrays of length m+1 in nums that match a given pattern of differences. For each window of size m+1, we can check if the sequence of differences between consecutive elements matches the pattern. Since the constraints are large, we can precompute the difference array and use a rolling hash or direct comparison for efficiency.
from typing import List
defcountMatchingSubarrays(nums: List[int], pattern: List[int]) -> int:
n, m = len(nums), len(pattern)
defsign(x):
return1if x >0else-1if x <0else0 diffs = [sign(nums[i+1] - nums[i]) for i in range(n-1)]
count =0for i in range(n - m -0):
if diffs[i:i+m] == pattern:
count +=1return count
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<vector>usingnamespace std;
intcountMatchingSubarrays(vector<int>& nums, vector<int>& pattern) {
int n = nums.size(), m = pattern.size(), res =0;
auto sign = [](int x) { return x >0?1: (x <0?-1:0); };
vector<int> diffs(n-1);
for (int i =0; i < n-1; ++i) diffs[i] = sign(nums[i+1] - nums[i]);
for (int i =0; i + m < n; ++i) {
bool match = true;
for (int j =0; j < m; ++j) {
if (diffs[i+j] != pattern[j]) { match = false; break; }
}
if (match) ++res;
}
return res;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
publicclassSolution {
publicintcountMatchingSubarrays(int[] nums, int[] pattern) {
int n = nums.length, m = pattern.length, res = 0;
int[] diffs =newint[n-1];
for (int i = 0; i < n-1; ++i) {
int d = nums[i+1]- nums[i];
diffs[i]= d > 0 ? 1 : (d < 0 ?-1 : 0);
}
for (int i = 0; i + m < n; ++i) {
boolean match =true;
for (int j = 0; j < m; ++j) {
if (diffs[i+j]!= pattern[j]) { match =false; break; }
}
if (match) ++res;
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
funcountMatchingSubarrays(nums: IntArray, pattern: IntArray): Int {
val n = nums.size
val m = pattern.size
val diffs = IntArray(n-1) { i ->when {
nums[i+1] > nums[i] ->1 nums[i+1] < nums[i] -> -1else->0 }
}
var res = 0for (i in0..n-m-1) {
if ((0 until m).all { diffs[i+it] == pattern[it] }) res++ }
return res
}