Count Occurrences in Fixed-Size Subarrays
Arrays & HashingAuto-graded · 22 test casesLast updated
Tests efficient sliding window maintenance to track element frequency across consecutive fixed-length subarrays.
Problem Statement
Given an array of integers data, a target value target, a window size window_size, and a minimum count min_count, find all positions where a contiguous subarray of length window_size contains at least min_count occurrences of target.
Return a list of starting indices (0-indexed) for all qualifying subarrays, in ascending order.
Constraints
1 <= len(data) <= 10^61 <= window_size <= len(data)0 <= target, data[i] <= 10^90 <= min_count <= window_size
Function Signature
def count_in_windows(data: List[int], target: int, window_size: int, min_count: int) -> List[int]:
pass
Examples
Example 1
Input: count_in_windows([1, 2, 1, 1, 3], 1, 3, 2)
Output: [0, 1, 2]
Example 2
Input: count_in_windows([4, 4, 4, 5], 4, 2, 2)
Output: [0, 1]
Hints
Hint 1
Recalculating the count for each window from scratch results in O(n·k) complexity, which is too slow for large inputs
Hint 2
When moving the window one position right, only two elements change: one enters and one exits
Hint 3
Maintain a running count that updates in constant time as the window slides
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
The core insight is that consecutive windows of fixed size overlap significantly. When the window moves one position to the right, window_size - 1 elements remain the same. Only one element exits on the left and one enters on the right.
Instead of recounting the target value in every window independently (which would take O(n·k) time), we maintain a running count that updates incrementally:
-
Initialize: Count the target occurrences in the first window
data[0:window_size]. If this count meets or exceedsmin_count, record index0. -
Slide: For each subsequent position, the window shifts right by one. The element at position
rightenters the window, and the element at positionright - window_sizeexits. Update the count by:- Adding 1 if the entering element equals
target - Subtracting 1 if the exiting element equals
target
- Adding 1 if the entering element equals
-
Check: After each update, if the count is at least
min_count, record the current window's starting index, which isright - window_size + 1.
This approach processes each element exactly once after the initial setup, achieving linear time complexity.
Why It Works
The algorithm maintains an invariant: after processing position right, count equals the exact number of times target appears in data[right - window_size + 1 : right + 1].
- The initial count is computed directly for the first window.
- Each subsequent count is derived from the previous one by accounting for the single element that enters and the single element that exits. Since all other elements are shared between consecutive windows, this incremental update produces the correct count.
Every possible window starting position from 0 to len(data) - window_size is examined exactly once, and indices are naturally produced in sorted order.
Complexity Analysis
- Time: O(n), where n is the length of
data. The initial window takes O(window_size) time, and the sliding loop performs O(1) work for each of the remaining n - window_size positions. - Space: O(1) auxiliary space, not counting the output list. In the worst case, the output can contain up to n - window_size + 1 indices.
Full Solution
from typing import List
def count_in_windows(data: List[int], target: int, window_size: int, min_count: int) -> List[int]:
# Count occurrences of target in the initial window
count = sum(value == target for value in data[:window_size])
result = [0] if count >= min_count else []
# Slide the window: add the entering element, remove the exiting element
for right in range(window_size, len(data)):
count += data[right] == target
count -= data[right - window_size] == target
if count >= min_count:
result.append(right - window_size + 1)
return result