#3036
Number of Subarrays That Match a Pattern II
HardArrayRolling HashString MatchingHash FunctionHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution transforms the nums array into a new array that represents the relationships between consecutive elements. This allows us to directly compare subarrays to the pattern using a sliding window approach, making it much faster.
⚙️
Algorithm
3 steps- 1Step 1: Create a new array nums2 where nums2[i] = 1 if nums[i + 1] > nums[i], nums2[i] = 0 if nums[i + 1] == nums[i], and nums2[i] = -1 if nums[i + 1] < nums[i].
- 2Step 2: Use a sliding window of size m to count how many times the pattern appears in nums2.
- 3Step 3: Compare each window of size m in nums2 to the pattern and count matches.
solution.py21 lines
1# Full working Python code
2
3def count_matching_subarrays(nums, pattern):
4 n = len(nums)
5 m = len(pattern)
6 nums2 = [0] * (n - 1)
7 for i in range(n - 1):
8 if nums[i + 1] > nums[i]:
9 nums2[i] = 1
10 elif nums[i + 1] == nums[i]:
11 nums2[i] = 0
12 else:
13 nums2[i] = -1
14 count = 0
15 for i in range(n - m - 1):
16 if nums2[i:i + m] == pattern:
17 count += 1
18 return count
19
20# Example usage
21print(count_matching_subarrays([1, 2, 3, 4, 5, 6], [1, 1])) # Output: 4ℹ
Complexity note: The time complexity is O(n) because we only traverse the nums array a couple of times, making it efficient for large inputs.
- 1Transforming the problem into a simpler form can significantly reduce complexity.
- 2Using a sliding window approach allows for efficient comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.