Number of Subarrays That Match a Pattern II - 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] if pattern[k] == 1
  • nums[i + k + 1] == nums[i + k] if pattern[k] == 0
  • nums[i + k + 1] < nums[i + k] if pattern[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], pattern = [1,1]
Output: 3
💡 Note: Three subarrays match: [1,2,3] (1<2<3), [2,3,4] (2<3<4), [3,4,5] (3<4<5). Each satisfies pattern [1,1] meaning both comparisons are increasing.
Example 2 — Mixed Pattern
$ Input: nums = [1,4,4,1,3,5], pattern = [1,0,-1]
Output: 1
💡 Note: Only subarray [1,4,4,1] matches: 1<4 (pattern[0]=1), 4=4 (pattern[1]=0), 4>1 (pattern[2]=-1).
Example 3 — No Matches
$ Input: nums = [1,2,3], pattern = [-1]
Output: 0
💡 Note: Pattern [-1] requires decreasing, but we have [1,2] and [2,3] which are both increasing. No matches found.

Constraints

  • 2 ≤ nums.length ≤ 106
  • 1 ≤ pattern.length ≤ nums.length - 1
  • pattern[i] is -1, 0, or 1
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Pattern Matching: Find subarrays that follow comparison rulesnums = [1,2,3,4,5]12345pattern = [1,1]111: increasing1: increasing[1,2,3]: 1<2<3 ✓[2,3,4]: 2<3<4 ✓[3,4,5]: 3<4<5 ✓Pattern [1,1] means: first < second < thirdResult: 3 matching subarrays found
Understanding the Visualization
1
Input Arrays
nums array and pattern of comparison rules
2
Pattern Matching
Check subarrays against pattern rules
3
Count Matches
Return total number of matching subarrays
Key Takeaway
🎯 Key Insight: Transform numeric comparisons into string pattern matching for efficient searching
Asked in
Google 25 Facebook 18 Microsoft 15
15.4K Views
Medium Frequency
~35 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen