Magicsheet logo

Number of Subarrays That Match a Pattern I

Medium
100%
Updated 6/1/2025

Number of Subarrays That Match a Pattern I

What is this problem about?

The Number of Subarrays That Match a Pattern I problem gives you an integer array nums and a pattern array where each pattern element is -1 (decrease), 0 (same), or 1 (increase). Count subarrays of nums whose consecutive differences match the pattern exactly. This coding problem uses rolling hash or KMP string matching after encoding nums's differences into a comparison string.

Why is this asked in interviews?

Uber, Visa, Amazon, and Google ask this because it requires transforming a numeric comparison problem into a string matching problem. By encoding each consecutive pair in nums as -1, 0, or 1, you get a comparison array that can be pattern-matched using KMP or rolling hash. The array, string matching, hash function, and rolling hash interview pattern is the core.

Algorithmic pattern used

Encode + KMP/Rolling hash. Create array encoded[i] = sign(nums[i+1] - nums[i]) for i=0..n-2 (values: -1, 0, or 1). Now count occurrences of pattern as a subarray in encoded using KMP or rolling hash. This transforms the problem from numeric to string matching.

Example explanation

nums=[1,2,3,4,2,3]. pattern=[1,1] (increase, increase). encoded=[1,1,1,-1,1] (differences: +1,+1,+1,-2,+1 → signs: 1,1,1,-1,1). Find [1,1] in [1,1,1,-1,1]: positions 0,1,2. Count = 4 (at positions 0,1,2,3? Let's check: [1,1] at index 0-1 ✓, 1-2 ✓, 2-3? [1,-1]✗. So count=2).

Common mistakes candidates make

  • Checking subarray matches with nested loops O(n*m).
  • Incorrect encoding: sign(diff) must be exactly -1, 0, or 1.
  • Off-by-one: encoded array has length n-1, pattern matches starting positions are 0..n-1-m.
  • Not using KMP/rolling hash for efficiency.

Interview preparation tip

Pattern matching on derived comparison sequences is a powerful reduction technique. Convert any "monotone comparison pattern" to a ternary string (-1,0,1), then apply KMP. This transformation makes the problem solvable with standard string matching algorithms. Practice encoding-then-matching for problems involving "detect ascending patterns," "detect wave patterns," and similar sequence recognition tasks.

Similar Questions