Subarray Sums Divisible by K
Given an integer array nums and an integer k, return the number of contiguous non-empty subarrays whose sum is divisible by k.
Open official problem prompt ↗Count how many contiguous subarrays have a sum that is an exact multiple of k.
Imagine a clock with k positions. Each element advances the hand by its value. Whenever the hand lands on a position it has visited before, the moves in between summed to a full number of loops, i.e. a multiple of k.
- Input
- nums = [4, 5, 0, -2, -3, 1], k = 5
- Output
- 7
- Why
- The seven subarrays with sum divisible by 5 are: [4,5,0,-2,-3], [5], [5,0], [5,0,-2,-3], [0], [0,-2,-3], and [-2,-3].
1 <= nums.length <= 3 * 10^4-10^4 <= nums[i] <= 10^42 <= k <= 10^4