Count of Subarrays with Sum Divisible by K

Asked atMorgan Stanley
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given an array of integers, nums, and an integer k, the task is to find the total number of subarrays whose sum is divisible by k. A subarray is a contiguous portion of the array.

Input: nums = [3, 1, 4, 1], k = 3 Output: 3 Explanation: The subarrays whose sum is divisible by 3 are: [3], [1, 4, 1], [3, 1, 4, 1].

Input: nums = [5, 10, -5, 20], k = 7 Output: 0 Explanation: There is no subarray whose sum is divisible by 7.

Input: nums = [4, 5, 0, -2, -3, 1], k = 5

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • 2 <= k <= 104

cpp

class Solution{
public:
    int subarraySumDivisbleByK(vector<int> &nums, int k){
        
    }
};

java

class Solution {
    public int subarraySumDivisbleByK(int[] nums, int k) {
        
    }
}

python

class Solution:
    def subarraySumDivisbleByK(self, nums, k):

javascript

class Solution {
    subarraySumDivisbleByK(nums, k) {
      
    }
}

csharp

public class Solution
{
    public int SubarraySumDivisibleByK(int[] nums, int k)
    {
        
    }
}

go

func subarraySumDivisbleByK(nums []int, k int) int {
	count := 0
	currentSum := 0
	remainderCounts := make(map[int]int)

	remainderCounts[0] = 1

	for _, num := range nums {
		currentSum += num
		remainder := currentSum % k

		if remainder < 0 {
			remainder += k
		}

		count += remainderCounts[remainder]

		remainderCounts[remainder]++
	}

	return count
}
Stuck? Show a way to structure it+
  1. 01Initialize frequency of remainder zero to one
  2. 02Update running sum and normalize its remainder
  3. 03Add previous frequency of that remainder to answer
  4. 04Increment the remainder frequency

Reference answer

Then expect these follow-ups

  • How would you count sums congruent to r?

    Tests: follow-up reasoning

  • Why is the initial zero frequency one?

    Tests: correctness reasoning

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question