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] 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,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
Pattern Matching in Subarrays INPUT nums = [1,2,3,4,5,6] 1 2 3 4 5 6 0 1 2 3 4 5 pattern = [1,1] 1 1 Pattern meaning: 1 = increasing 0 = equal -1 = decreasing Subarray size needed: m + 1 = 2 + 1 = 3 ALGORITHM STEPS 1 Convert to Diff String Compare adjacent elements nums: 1 2 3 4 5 6 diff: 1 1 1 1 1 2 Create Pattern String pattern [1,1] --> "11" 3 Find All Matches Search "11" in "11111" diff = "11111" pos 0: [11]111 OK pos 1: 1[11]11 OK pos 2: 11[11]1 OK pos 3: 111[11] OK 4 Count Matches Total = 4 subarrays FINAL RESULT Matching Subarrays: [1,2,3] 1->2->3 increasing indices 0-2 [2,3,4] 2->3->4 increasing indices 1-3 [3,4,5] 3->4->5 increasing indices 2-4 [4,5,6] 4->5->6 increasing indices 3-5 Output: 4 subarrays match OK - Verified Key Insight: Convert the comparison pattern into a string matching problem. Transform nums into a difference string where each character represents the relationship between adjacent elements (1=up, 0=same, -1=down). Then count occurrences of the pattern string. Time: O(n*m), Space: O(n). TutorialsPoint - Number of Subarrays That Match a Pattern I | Pattern String Matching Approach
Asked in
Google 25 Microsoft 20 Amazon 15
28.5K Views
Medium Frequency
~25 min Avg. Time
890 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