Number of Subarrays That Match a Pattern II - Problem
Pattern Matching in Subarrays
Imagine you're analyzing stock market trends! You have an array of stock prices
Given:
• A
• A
A subarray
•
•
•
Return the count of matching subarrays.
Imagine you're analyzing stock market trends! You have an array of stock prices
nums and a pattern that describes the desired trend behavior. Your task is to find how many consecutive subsequences of prices match this exact trend pattern.Given:
• A
nums array of size n representing values• A
pattern array of size m with values -1, 0, or 1A subarray
nums[i..j] of size m + 1 matches the pattern if:•
pattern[k] = 1: next value is greater (upward trend)•
pattern[k] = 0: next value is equal (flat trend)•
pattern[k] = -1: next value is smaller (downward trend)Return the count of matching subarrays.
Input & Output
example_1.py — Basic Pattern Match
$
Input:
nums = [1, 2, 3, 4, 5, 6], pattern = [1, 1]
›
Output:
4
💡 Note:
Subarrays [1,2,3], [2,3,4], [3,4,5], [4,5,6] all match pattern [1,1] as each has consecutive increasing elements
example_2.py — Mixed Pattern
$
Input:
nums = [1, 4, 4, 1, 3, 5, 5, 3], pattern = [1, 0, -1]
›
Output:
2
💡 Note:
Subarrays [1,4,4,1] and [3,5,5,3] match pattern [1,0,-1]: increase, stay same, then decrease
example_3.py — No Matches
$
Input:
nums = [1, 2, 3, 4], pattern = [-1, -1]
›
Output:
0
💡 Note:
No subarray has two consecutive decreasing transitions since nums is strictly increasing
Visualization
Tap to expand
Understanding the Visualization
1
Analyze Transitions
Convert consecutive number comparisons to trend symbols
2
Pattern Recognition
Use string matching algorithms to find trend pattern occurrences
3
Count Matches
Return the total count of matching subsequences
Key Takeaway
🎯 Key Insight: Transform numeric comparisons into string patterns, then leverage efficient string matching algorithms like KMP for optimal O(n+m) performance.
Time & Space Complexity
Time Complexity
O(n + m)
Building trend string takes O(n), KMP preprocessing takes O(m), and matching takes O(n)
✓ Linear Growth
Space Complexity
O(n + m)
Space for trend string O(n) and failure function O(m)
⚡ Linearithmic Space
Constraints
- 2 ≤ nums.length ≤ 106
- 1 ≤ nums[i] ≤ 109
- 1 ≤ pattern.length ≤ 106
- pattern[i] is -1, 0, or 1
- The pattern array describes transitions between consecutive elements
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code