Count how many contiguous subarrays follow a given up/down/equal pattern between adjacent elements.
You are given an integer array nums and a pattern array pattern of length m, where each value in pattern is one of -1, 0, or 1.
Consider any contiguous subarray of nums with length m + 1. For every adjacent pair inside that subarray, compare the two numbers:
-1if the left number is smaller than the right number0if they are equal1if the left number is larger than the right number
A subarray matches the pattern if these comparisons, in order, are exactly equal to pattern.
Your task is to count how many subarrays of length m + 1 match the pattern.
Input Format
Input
- An integer array
nums - An integer array
patterncontaining only-1,0, and1
Interpretation
For each contiguous subarray of nums with length pattern.length + 1, compute the sign of each adjacent difference and compare it with pattern.
Output Format
Output
- Return the number of contiguous subarrays that match the pattern exactly.
Constraints
1 <= nums.length1 <= pattern.length < nums.lengthpattern[i]is one of-1,0,1- The answer fits in a 32-bit signed integer
Example 1
Input
nums = [1,2,3,4,5], pattern = [1,1,1,1]
Output
4
Explanation
The adjacent comparisons are [1, 1, 1, 1], so every subarray of length 5 matches. There are 4 valid starting positions in the full array example as written here.
Example 2
Input
nums = [1,1,2,1], pattern = [0,1,-1]
Output
1
Explanation
For the subarray [1,1,2,1], the comparisons are [0, 1, -1], which matches the pattern exactly.
Show 1 more example
Example 3
Input
nums = [1,2,2,3], pattern = [1,0]
Output
1
Explanation
The subarray [1,2,2] gives comparisons [1, 0], so it matches once.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.