Count Subarrays Whose Step-by-Step Changes Match an Up, Flat, Down Pattern
Capital OneSoftware Engineer · Online AssessmentLast updated
Count the fixed-length windows of an integer array whose consecutive rises, equal steps, and drops follow a given pattern of 1, 0, and -1 values, counting overlapping matches separately. Tests turning a comparison rule into an exact window check with correct index bounds.
You are given an integer array nums of length n and an array pattern of length m whose values are each -1, 0 or 1. Each pattern value describes the relationship between two neighboring numbers:
1: the next number is strictly greater than the current one;0: the next number is equal to the current one;-1: the next number is strictly smaller than the current one.
The contiguous subarray of nums that starts at index i and has exactly m + 1 elements matches the pattern if, for every k from 0 to m - 1, the relationship between nums[i + k] and nums[i + k + 1] is the one described by pattern[k]. Return the number of starting indices i whose subarray matches.
Function Signature
def count_matching_subarrays(nums: list[int], pattern: list[int]) -> int:
Rules
- Only subarrays of exactly
m + 1elements are considered, one for each starting indexiwith0 <= i <= n - m - 1. - Matching subarrays may overlap; each matching starting index counts once.
- Return
0if no subarray matches.
Constraints
2 <= n <= 1001 <= m < n1 <= nums[i] <= 10^9- Every
pattern[k]is one of-1,0or1.
Examples
Example 1
Input: nums = [1, 3, 2, 4, 3, 3], pattern = [1, -1]
Output: 2
The subarrays of length 3 are [1, 3, 2] (up, then down: matches), [3, 2, 4] (down, then up), [2, 4, 3] (up, then down: matches) and [4, 3, 3] (down, then equal).
Example 2
Input: nums = [5, 5, 5, 5], pattern = [0, 0]
Output: 2
The subarrays starting at indices 0 and 1 are both [5, 5, 5]. They overlap, and each counts.
Example 3
Input: nums = [4, 3, 2, 1], pattern = [1]
Output: 0
Every neighboring pair decreases, so no subarray of length 2 rises.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.