974. Subarray Sums Divisible by K
mediumCount the number of non-empty subarrays whose sum is divisible by k. A canonical prefix-sum-plus-hash-map problem that hinges on grouping by remainder modulo k.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
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.
Constraints
1 <= nums.length <= 3 * 10^4-10^4 <= nums[i] <= 10^42 <= k <= 10^4
Examples
Example 1
nums = [4,5,0,-2,-3,1], k = 57Explanation: 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
nums = [5], k = 90Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
A subarray nums[i..j] has sum prefix[j+1] - prefix[i]. When is that difference divisible by k?
Hint 2
Two prefix sums share the same remainder modulo k iff their difference is divisible by k. Group prefixes by remainder.
Hint 3
Handle negative remainders by normalising: ((r % k) + k) % k so that -3 mod 5 becomes 2, not -3.
Solution approach
Reveal approach
Compute running prefix sums and look at each prefix's remainder modulo k. Two prefix sums having the same remainder means the subarray strictly between them sums to a multiple of k. Maintain a hash map (or fixed-size array of length k) counting how many times each remainder has been seen, seeded with remainder 0 -> 1 to credit subarrays starting at index 0. Walk the array once: at each step compute the normalised remainder of the running sum, add the current count for that remainder to the answer, then increment the count. Normalisation is critical for negative numbers — use ((sum % k) + k) % k so that -3 with k=5 becomes 2 rather than -3, otherwise pairs across sign boundaries are miscounted.
Complexity
- Time
- O(n)
- Space
- O(k)
Related patterns
- prefix-sum
- hash-map
- modular-arithmetic
Related problems
- 560. Subarray Sum Equals K
- 523. Continuous Subarray Sum
- 525. Contiguous Array
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Meta
Practice these live with InterviewChamp.AI
Drill Subarray Sums Divisible by K and Arrays problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →