Loading section...
Prefix Sums with Modular Arithmetic
Concepts: pyModularPrefixSum, pyNegativeModulo, pySubarrayDivisible
Count subarrays whose sum is divisible by K. This is a variant of the prefix sum + hash map problem, but with a modulo twist that makes it significantly more subtle -- especially with negative numbers. The core insight: sum(i..j) is divisible by K if and only if (prefix[j+1] - prefix[i]) is divisible by K, which means prefix[j+1] % K == prefix[i] % K. So instead of hashing the full prefix sum, you hash the prefix sum modulo K. But Python's modulo and negative-number behavior requires careful handling. Count Subarrays Divisible by K (LeetCode 974) The Negative Number Trap In Python, the % operator always returns a non-negative result when K is positive: (-7) % 5 = 3 in Python (because -7 = -2*5 + 3). This is the correct mathematical modulo. In C++ and Java, (-7) % 5 = -2 (truncation toward