Number of Subarrays That Match a Pattern I - Problem
You are given two arrays: an integer array nums of size n and a pattern array pattern of size m containing only the values -1, 0, and 1.
Your task is to find how many subarrays of nums match the given pattern. A subarray nums[i..j] of length m + 1 matches the pattern if:
- When
pattern[k] == 1:nums[i + k + 1] > nums[i + k](increasing) - When
pattern[k] == 0:nums[i + k + 1] == nums[i + k](equal) - When
pattern[k] == -1:nums[i + k + 1] < nums[i + k](decreasing)
For example, if pattern is [1, 0, -1], you're looking for subarrays where the first pair increases, the second pair stays equal, and the third pair decreases.
Return the count of all such matching subarrays.
Input & Output
example_1.py โ Basic Pattern Matching
$
Input:
nums = [1,2,3,4,5,6], pattern = [1,1]
โบ
Output:
4
๐ก Note:
The pattern [1,1] means we need two consecutive increases. Matching subarrays are: [1,2,3], [2,3,4], [3,4,5], [4,5,6]
example_2.py โ Mixed Pattern
$
Input:
nums = [1,4,4,1,3,5], pattern = [1,0,-1]
โบ
Output:
1
๐ก Note:
Pattern [1,0,-1] means increase, stay same, decrease. Only [1,4,4,1] matches: 1<4 (increase), 4==4 (same), 4>1 (decrease)
example_3.py โ No Matches
$
Input:
nums = [1,2,3,4], pattern = [-1,-1]
โบ
Output:
0
๐ก Note:
Pattern [-1,-1] requires two consecutive decreases, but the array [1,2,3,4] is strictly increasing, so no subarrays match
Visualization
Tap to expand
Understanding the Visualization
1
Identify Pattern
Understanding what relationships between consecutive elements we're looking for
2
Slide Through Array
Check each possible starting position for a subarray of the required length
3
Verify Relationships
For each position, compare consecutive pairs against the pattern requirements
4
Count Matches
Increment counter for each subarray that perfectly matches the pattern
Key Takeaway
๐ฏ Key Insight: Pattern matching requires checking consecutive element relationships sequentially - we slide through possible starting positions and verify each pattern element matches the corresponding pair relationship.
Time & Space Complexity
Time Complexity
O(n*m)
We check n-m possible starting positions, and for each position we verify m pattern elements
โ Linear Growth
Space Complexity
O(1)
Only using a few variables for counting and iteration, no additional data structures needed
โ Linear Space
Constraints
- 1 โค nums.length โค 106
- 0 โค pattern.length < nums.length
- 1 โค nums[i] โค 109
- pattern[i] โ {-1, 0, 1}
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code