Subarray Sums Divisible by K
1 approach, code in every language
Problem description
You are given an integer array nums and an integer k. Return the number of contiguous subarrays whose element sum is divisible by k.
Because the array can contain negative numbers, take care to normalize remainders into the range [0, k) so that two prefixes that are congruent modulo k are grouped together correctly.
Example 1
Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7
There are seven subarrays with a sum divisible by 5, including the whole array [4,5,0,-2,-3,1] and the singleton subarrays [5] and [0].
Example 2
Input: nums = [5], k = 9
Output: 0
The only subarray is [5], whose sum 5 is not divisible by 9.
Constraints
1 <= nums.length <= 3 * 10^4-10^4 <= nums[i] <= 10^42 <= k <= 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Full Turn Command Blocks is our own problem on the technique behind Subarray Sums Divisible by K: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free