KatInterview

Subarrays Whose Matching-Element Count Hits a Residue

Arrays & HashingAuto-graded · 19 test cases
MediumAuto-gradedArrays & Hashingprefix-sumhash-mapmodular-arithmetic

Last updated

Count subarrays where the number of elements congruent to a residue, taken modulo the same base, equals that residue, using prefix remainders and a frequency table.

You are given an integer list values and two integers mod and residue, with 0 <= residue < mod.

An element is called a match if dividing it by mod leaves remainder residue, that is, x % mod == residue. The remainder is the mathematical non-negative one, so for a negative x the remainder is still in the range [0, mod).

A non-empty contiguous subarray is good if the number of matches inside it, taken modulo mod, equals residue.

Return how many subarrays of values are good. Subarrays are counted by their position (start and end index), so two equal-looking subarrays at different positions count separately.

Note that residue plays two independent roles: it decides which elements are matches, and it is also the remainder the match count must have. A subarray with zero matches is good exactly when residue == 0.

An empty list has no subarrays, so the answer is 0.

The answer can be large, so make sure your approach does not rely on fixed-width integer limits.

A quadratic enumeration of all subarrays is too slow for the largest inputs.

Constraints

  • 0 <= len(values) <= 10^5
  • 1 <= mod <= 10^9
  • 0 <= residue < mod
  • Each element of values fits in a signed 32-bit integer (it may be negative).
  • The function returns a single integer.

Examples

Example 1

Input: count_good_subarrays([3, 1, 9, 6], 3, 0)

Output: 2

Hints

Hint 1

Turn each element into 0 or 1 depending on whether it is a match. The number of matches in a subarray is then a difference of two prefix sums.

Hint 2

A subarray from prefix index l to prefix index r is good when (P[r] - P[l]) mod m == residue, which means P[l] mod m == (P[r] - residue) mod m. Count earlier prefixes with that remainder.

Hint 3

Start the frequency table with the empty prefix (remainder 0), query it before inserting the current prefix so you never count an empty subarray, and use a dictionary if mod is huge.