Subarray Sums Divisible by K - 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.

Example: If nums = [4,5,0,-2,-3,1] and k = 5, the subarrays with sums divisible by 5 are: [5] (sum=5), [5,0] (sum=5), [5,0,-2,-3] (sum=0), [0] (sum=0), [-2,-3] (sum=-5), and [4,5,0,-2,-3,1] (sum=5). Answer is 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7
💡 Note: The subarrays with sums divisible by 5 are: [5] (sum=5), [5,0] (sum=5), [5,0,-2,-3] (sum=0), [0] (sum=0), [-2,-3] (sum=-5), [4,5,0,-2,-3,1] (sum=5), and one more subarray for a total of 7.
Example 2 — Small Array
$ Input: nums = [5], k = 9
Output: 0
💡 Note: The only subarray is [5] with sum 5, which is not divisible by 9.
Example 3 — Multiple Divisible
$ Input: nums = [2,4,3], k = 6
Output: 2
💡 Note: Subarrays with sums divisible by 6: [2,4] (sum=6). The answer is 1.

Constraints

  • 1 ≤ nums.length ≤ 3 × 104
  • -104 ≤ nums[i] ≤ 104
  • 2 ≤ k ≤ 104

Visualization

Tap to expand
Subarray Sums Divisible by K INPUT nums array: 4 i=0 5 i=1 0 i=2 -2 i=3 -3 i=4 1 i=5 k = 5 Prefix Sums: [0, 4, 9, 9, 7, 4, 5] Prefix Sum % k: [0, 4, 4, 4, 2, 4, 0] Find subarrays with sum % k == 0 ALGORITHM (Hash) 1 Initialize HashMap map[0] = 1, count = 0 2 Calculate Prefix Sum sum += nums[i] 3 Get Remainder rem = ((sum % k) + k) % k 4 Update Count + Map count += map[rem] Final HashMap: rem count pairs 0 2 C(2,2)=1 2 1 0 4 4 C(4,2)=6 Total = 1 + 0 + 6 = 7 FINAL RESULT Output: 7 7 Valid Subarrays: 1. [4,5,0,-2,-3,1] sum=5 2. [5] sum=5 3. [5,0] sum=5 4. [5,0,-2,-3] sum=0 5. [0] sum=0 6. [0,-2,-3] sum=-5 7. [-2,-3] sum=-5 All sums divisible by 5 OK - Verified Key Insight: If two prefix sums have the same remainder when divided by k, their difference is divisible by k. Use a hashmap to count remainders. For each remainder r appearing n times, we get C(n,2) = n*(n-1)/2 pairs. Time: O(n) | Space: O(k) - where n is array length and k is the divisor TutorialsPoint - Subarray Sums Divisible by K | Hash Approach
Asked in
Facebook 25 Google 20 Amazon 15
85.6K Views
Medium Frequency
~25 min Avg. Time
2.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen