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
Number of Subarrays That Match a Pattern II INPUT nums = [1,2,3,4,5] 1 2 3 4 5 0 1 2 3 4 pattern = [1,1] 1 1 Pattern meaning: 1 = next element greater 0 = next element equal -1 = next element smaller Subarray size needed: m + 1 = 3 elements ALGORITHM STEPS 1 Convert nums to diff array Compare adjacent: sign(nums[i+1]-nums[i]) 1 1 1 1 diff = [1,1,1,1] 2 Use KMP / Z-algorithm Pattern matching on diff array 3 Find pattern occurrences Search [1,1] in [1,1,1,1] i=0 i=1 i=2 4 Count matches Total valid subarrays found FINAL RESULT Matching Subarrays: 1 2 3 OK [1,2,3] -- 1<2, 2<3 2 3 4 OK [2,3,4] -- 2<3, 3<4 3 4 5 OK [3,4,5] -- 3<4, 4<5 Output: 3 Key Insight: Transform the problem into string matching: Convert nums to a difference pattern array where each element represents the relationship between consecutive numbers (1, 0, or -1). Then use KMP or Z-algorithm for O(n+m) pattern matching instead of O(n*m) brute force approach. TutorialsPoint - Number of Subarrays That Match a Pattern II | Optimal Solution (KMP/Z-Algorithm)
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