DEV Community

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

Posted on

1

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)

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay