Count Sliding Windows Matching a Step-Direction Sequence
StringsAuto-graded · 23 test casesLast 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] == 1requiresnums[s + i + 1] > nums[s + i](strictly increasing step)directions[i] == 0requiresnums[s + i + 1] == nums[s + i](flat step)directions[i] == -1requiresnums[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, sosruns from0up to and includinglen(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^51 <= len(directions) < len(nums)-10^9 <= nums[i] <= 10^9- Every
directions[i]is1,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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1 — Reduce to pattern matching on a sign sequence
Each entry of directions says something about the relationship between two neighbours in nums, not about their actual values. So the first move is to discard the raw values entirely and replace each consecutive pair (nums[i], nums[i+1]) with its sign:
sign = +1 if nums[i+1] > nums[i]
0 if nums[i+1] == nums[i]
-1 if nums[i+1] < nums[i]
This produces a signs array of length n - 1 over the three-symbol alphabet {-1, 0, 1}. A block of nums starting at s matches directions if and only if signs[s : s + p] == directions. The problem is now: count all starting positions (including overlapping ones) where directions appears as a contiguous sub-array of signs. That is exactly substring search, with a three-symbol alphabet instead of letters.
Step 2 — Why brute force can be too slow
Checking every starting position against the full directions array takes O(n·m) time. With n = 10^5 and p close to n/2, that is around 2.5 × 10^9 comparisons in the worst case — for example, nums all equal with an all-zero directions array. A linear-time algorithm is needed.
Step 3 — KMP in one pass
Failure function. Preprocess directions into a fail table where fail[i] is the length of the longest proper prefix of directions[0..i] that is also a suffix of it. Building this table is O(p).
Scan. Walk through signs while tracking k, the number of direction symbols currently matched:
- If
signs[j]equalsdirections[k], incrementk. - If they differ and
k > 0, fall back tok = fail[k - 1]and retry (this is the core KMP step — it never backtracks past what is still useful). - When
kreachesp, a full match has been found. Count it, then setk = fail[p - 1]rather than 0. This preserves whichever prefix ofdirectionsoverlaps with a potential next match.
Why this is correct
- The sign reduction is a one-to-one correspondence: each valid starting index in
numsmaps to exactly one starting position insigns. - The KMP invariant guarantees that after processing
signs[j],kequals the length of the longest prefix ofdirectionsthat is a suffix ofsigns[0..j]. No match can be skipped. - Resetting to
fail[p - 1]instead of 0 ensures overlapping occurrences are counted, which is why the all-equal example returns 2 instead of 1.
Complexity
- Time: O(n + p) — building
signsis O(n), the failure table is O(p), and the scan is O(n) amortised (k increases by at most 1 per symbol, and every fallback strictly decreases it). - Space: O(n + p) for
signsandfail. Signs could be computed on the fly to bring extra space down to O(p), but it is not required.
Edge cases
- Only one possible window (
p == n - 1): KMP returns 0 or 1 naturally. - All-equal input with all-zero
directions: the heaviest overlap scenario; the failure-function reset handles it correctly. p == 1:fail = [0]; the scan simply counts positions wheresigns[i] == directions[0].- Values near ±10^9: only comparisons are performed, never subtraction, so there is no overflow risk.
Full solution
from typing import List
def count_matching_windows(nums: List[int], directions: List[int]) -> int:
# Convert nums into a sequence of step signs over the alphabet {-1, 0, 1}.
# sign[i] describes the relationship between nums[i+1] and nums[i].
signs = [(b > a) - (b < a) for a, b in zip(nums, nums[1:])]
p = len(directions)
# Build the KMP failure (partial-match) table for directions.
# fail[i] = length of the longest proper prefix of directions[0..i]
# that is also a suffix of directions[0..i].
fail = [0] * p
k = 0
for i in range(1, p):
while k and directions[i] != directions[k]:
k = fail[k - 1]
if directions[i] == directions[k]:
k += 1
fail[i] = k
# Scan signs for all occurrences of directions, including overlapping ones.
count = 0
k = 0
for x in signs:
while k and x != directions[k]:
k = fail[k - 1]
if x == directions[k]:
k += 1
if k == p:
count += 1
# Fall back via the failure table rather than resetting to 0,
# so that any overlapping match starting inside this one is not lost.
k = fail[k - 1]
return count