974. Subarray Sums Divisible by K
Description
Given an integer array nums
and an integer k
, return the number of non-empty subarrays that have a sum divisible by k
.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [4,5,0,-2,-3,1], k = 5 Output: 7 Explanation: There are 7 subarrays with a sum divisible by k = 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Example 2:
Input: nums = [5], k = 9 Output: 0
Constraints:
1 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
2 <= k <= 104
Solutions
Solution 1: Hash Table + Prefix Sum
-
Key Insight:
- If there exist indices $i$ and $j$ such that $i \leq j$, and the sum of the subarray $nums[i, ..., j]$ is divisible by $k$, then $(s_j - s_i) \bmod k = 0$, this implies: $s_j \bmod k = s_i \bmod k$
- We can use a hash table to count the occurrences of prefix sums modulo $k$ to efficiently check for subarrays satisfying the condition.
-
Prefix Sum Modulo:
- Use a hash table $cnt$ to count occurrences of each prefix sum modulo $k$.
- $cnt[i]$ represents the number of prefix sums with modulo $k$ equal to $i$.
- Initialize $cnt[0] = 1$ to account for subarrays directly divisible by $k$.
-
Algorithm:
- Let a variable $s$ represent the running prefix sum, starting with $s = 0$.
- Traverse the array $nums$ from left to right.
- For each element $x$:
- Compute $s = (s + x) \bmod k$.
- Update the result: $ans += cnt[s]$.
- Increment $cnt[s]$ by $1$.
- For each element $x$:
- Return the result $ans$.
Note: if $s$ is negative, adjust it to be non-negative by adding $k$ and taking modulo $k$ again.
The time complexity is $O(n)$ and space complexity is $O(n)$ where $n$ is the length of the array $nums$.
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|