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^4See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI