Skip to main content
Back to problems
Leetcode
Medium
Arrays
Number Of Subarrays That Match A Pattern I

Count how many contiguous subarrays follow a given up/down/equal pattern between adjacent elements.

Acceptance 0%
Problem Statement

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:

  • -1 if the left number is smaller than the right number
  • 0 if they are equal
  • 1 if 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 pattern containing only -1, 0, and 1

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.length
  • 1 <= pattern.length < nums.length
  • pattern[i] is one of -1, 0, 1
  • The answer fits in a 32-bit signed integer
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.