Skip to main content
Back to problems
#3034
Medium Algorithms

Number of subarrays that match a pattern i

Array Rolling Hash String Matching Hash Function
68.4% acceptance
Feb 25, 2026
124
19
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_matching_subarrays(nums: Vec<i32>, pattern: Vec<i32>) -> i32 {
    let n = nums.len();
    let m = pattern.len();
    let mut count = 0;
    'outer: for i in 0..=(n-m-1) {
      for k in 0..m {
        let diff = nums[i+k+1].cmp(&nums[i+k]) as i32;
        if diff != pattern[k] { continue 'outer; }
      }
      count += 1;
    }
    count
  }
}