Subarray sums divisible by k
Standard · Write code · about 15 min
Given an integer array nums and an integer k, return how many non-empty subarrays have a sum divisible by k. A subarray is a run of neighbouring cells.
Two prefix sums with the same remainder mod k differ by a multiple of k, so the cells between them form such a subarray.
Example 1
Input:
[[4,5,0,-2,-3,1],5]
Output:
7
The 7 subarrays include [5], [5, 0], [0, -2, -3] and [4, 5, 0, -2, -3, 1].
Example 2
Input:
[[5],9]
Output:
0
Constraints
- 0 ≤ nums.length ≤ 10,000
- -10,000 ≤ nums[i] ≤ 10,000
- 1 ≤ k ≤ 10,000
Learn the idea first: Hash maps for lookup and counting, a visual lesson.
More Hash maps for lookup and counting problems
- Contains duplicate Warm-up
- Fill the seen-set Warm-up
- Isomorphic strings Standard
- Longest consecutive sequence Challenge