Number of Subarrays That Match a Pattern I - Problem
You are given a 0-indexed integer array nums of size n, and a 0-indexed integer array pattern of size m consisting of integers -1, 0, and 1.
A subarray nums[i..j] of size m + 1 is said to match the pattern if the following conditions hold for each element pattern[k]:
nums[i + k + 1] > nums[i + k]ifpattern[k] == 1nums[i + k + 1] == nums[i + k]ifpattern[k] == 0nums[i + k + 1] < nums[i + k]ifpattern[k] == -1
Return the count of subarrays in nums that match the pattern.
Input & Output
Example 1 — Basic Pattern Match
$
Input:
nums = [1,2,3,4,5,6], pattern = [1,1]
›
Output:
4
💡 Note:
Four subarrays match: [1,2,3] (1<2<3), [2,3,4] (2<3<4), [3,4,5] (3<4<5), [4,5,6] (4<5<6)
Example 2 — Mixed Pattern
$
Input:
nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
›
Output:
2
💡 Note:
Two subarrays match: [1,4,4,1] (1<4=4>1) and [3,5,5,3] (3<5=5>3)
Example 3 — No Matches
$
Input:
nums = [1,2,3,4], pattern = [-1,-1]
›
Output:
0
💡 Note:
No subarray of length 3 has consecutive decreasing elements
Constraints
- 1 ≤ nums.length ≤ 106
- 1 ≤ pattern.length ≤ nums.length
- 1 ≤ nums[i] ≤ 109
- -1 ≤ pattern[i] ≤ 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,2,3,4,5,6] and pattern [1,1]
2
Process
Find subarrays of length 3 where consecutive pairs match pattern
3
Output
Count of matching subarrays = 4
Key Takeaway
🎯 Key Insight: Transform numeric comparisons into pattern symbols for efficient string matching algorithms
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code