KatInterview

Count Sliding Windows Matching a Step-Direction Sequence

StringsAuto-graded · 23 test cases
MediumAuto-gradedStringsstring-matchingkmparrays

Last updated

Tests whether a candidate can reduce pairwise comparisons to a sign sequence and count all overlapping pattern matches in linear time using KMP.

You are given an integer array nums and a directions array whose every element is exactly 1, 0, or -1.

Let p = len(directions). For each starting index s in nums, consider the block of p + 1 consecutive values nums[s], nums[s+1], ..., nums[s+p]. That block matches directions when, for every position i from 0 to p - 1:

  • directions[i] == 1 requires nums[s + i + 1] > nums[s + i] (strictly increasing step)
  • directions[i] == 0 requires nums[s + i + 1] == nums[s + i] (flat step)
  • directions[i] == -1 requires nums[s + i + 1] < nums[s + i] (strictly decreasing step)

All p conditions must hold simultaneously; a single wrong step disqualifies the block.

Return the total count of starting indices s whose block matches directions.

Rules

  • A valid block must fit entirely within nums, so s runs from 0 up to and including len(nums) - p - 1.
  • Blocks are allowed to overlap; each valid starting index contributes 1 to the answer regardless of how many other blocks it overlaps with.
  • If no block matches, return 0.

Constraints

  • 2 <= len(nums) <= 10^5
  • 1 <= len(directions) < len(nums)
  • -10^9 <= nums[i] <= 10^9
  • Every directions[i] is 1, 0, or -1

Examples

Example 1

Input: count_matching_windows([3, 7, 5, 5, 8, 7], [-1, 0, 1])

Output: 1

Example 2

Input: count_matching_windows([2, 2, 2, 2], [0, 0])

Output: 2

Example 3

Input: count_matching_windows([5, 4, 5, 4, 5], [1, -1])

Output: 1

Hints

Hint 1

Instead of comparing raw values inside every window, first convert nums into a shorter array of step signs (+1, 0, or -1 for each consecutive pair). The problem then becomes: how many times does the directions array appear as a contiguous sub-sequence of that sign array?

Hint 2

A naive scan that checks every starting position against the full directions array is O(n·m). Think about whether worst-case inputs (e.g., all equal values with an all-zero directions array) could make that too slow, and whether a linear-time pattern-matching algorithm applies here.

Hint 3

When you find a complete match, resist resetting your matched-length counter all the way back to zero. Doing so misses overlapping matches. Instead, use the KMP failure function to jump back only as far as necessary, preserving any prefix of directions that is also a valid suffix of what you have already scanned.