Number of Subarrays That Match a Pattern II

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.

Example 1
Inputnums = [1,2,3,4,5,6], pattern = [1,1]
Output4
The pattern [1,1] indicates strictly increasing subarrays of size 3, and [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match it.
Example 2
Inputnums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
Output2
The subarrays [1,4,4,1] and [3,5,5,3] match the pattern [1,0,-1], so there are 2 matches.

Constraints

  • 2 <= n == nums.length <= 10^6
  • 1 <= nums[i] <= 10^9
  • 1 <= m == pattern.length < n
  • -1 <= pattern[i] <= 1

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate