Subarrays Whose Matching-Element Count Hits a Residue
Arrays & HashingAuto-graded · 19 test casesLast 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^51 <= mod <= 10^90 <= residue < mod- Each element of
valuesfits 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Replace each element with an indicator: 1 if x % mod == residue, else 0. The number of matches in a subarray is then the difference of two prefix sums. Let P[k] be the number of matches among the first k elements, with P[0] = 0. The subarray covering positions l..r has P[r+1] - P[l] matches, and it is good when
(P[r+1] - P[l]) mod m == residue, equivalently P[l] mod m == (P[r+1] - residue) mod m.
So, sweeping left to right, for each right end we only need to know how many earlier prefixes have a particular remainder. We keep a frequency table of prefix remainders:
- Seed it with remainder 0 for the empty prefix.
- For each element, update the running prefix remainder if the element is a match.
- Add the table entry for
(prefix - residue) % modto the answer. - Record the current prefix remainder in the table.
Why it is correct
- Each subarray corresponds to exactly one pair of prefix indices
(l, r+1)withl < r+1, so each is counted once. - Querying before inserting means the table holds only prefixes
P[0..r], exactly the valid left ends, and never pairs a prefix with itself (which would be an empty subarray). - Validity depends only on the difference of prefix counts modulo
mod, so keeping the prefix reduced modulomodloses nothing. - Python's
%returns a value in[0, mod)for positivemod, so the lookup key is always a valid remainder, even whenprefix < residue.
A sliding window does not work because the match count wraps around modulo mod, so validity is not monotonic in window size.
Complexity
- Time: O(n), one pass with O(1) dictionary work per element.
- Space: O(min(n, mod)), since at most n + 1 distinct remainders can appear. Using a dictionary rather than an array of size
modkeeps memory small whenmodis as large as 10^9.
Reference solution
from typing import List
from collections import defaultdict
def count_good_subarrays(values: List[int], mod: int, residue: int) -> int:
# seen[r] = number of prefixes so far whose match count % mod == r
seen = defaultdict(int)
seen[0] = 1 # the empty prefix
prefix = 0
answer = 0
for x in values:
if x % mod == residue:
prefix = (prefix + 1) % mod
# Need an earlier prefix with remainder (prefix - residue) mod `mod`
answer += seen[(prefix - residue) % mod]
# Insert current prefix only after querying
seen[prefix] += 1
return answer