KatInterview

Count Occurrences in Fixed-Size Subarrays

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingsliding-windowarrayfrequency-counting

Last 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^6
  • 1 <= window_size <= len(data)
  • 0 <= target, data[i] <= 10^9
  • 0 <= 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