DEV Community

Cover image for 974. Subarray Sums Divisible by K
Harsh Rajpal
Harsh Rajpal

Posted on

974. Subarray Sums Divisible by K

Problem Statement:
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 1:

Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7
Explanation: 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:

Input: nums = [5], k = 9
Output: 0

Constraints:

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

Solution:

Algorithm:

  1. Create a count array of size k and initialize all elements as 0.
  2. Initialize sum of elements as 0 and count of subarrays as 0.
  3. Iterate through the array and for every element arr[i], do following. a) Increment sum by arr[i]. b) If k is non-zero, then update sum as sum = sum % k. c) Increment count of current sum. d) Add count[sub_sum] to the result. e) Increment count[sub_sum] by 1.
  4. Return result.

Code:

public class Solution {
    public int subarrayDivByK(int[] nums, int k){
        int[] count = new int[k];
        count[0] = 1;
        int sum = 0;
        int ans = 0;
        for(int i = 0; i < nums.length; i++){
            sum += nums[i];
            int mod = (sum % k + k) % k;
            ans += count[mod];
            count[mod]++;
        }
        return ans;
    }

}
Enter fullscreen mode Exit fullscreen mode

Time Complexity:
O(N)
Space Complexity:
O(K)

Top comments (0)