The Indian Engineer

Problem 974 Subarray Sums Divisible by K

Posted on 6 mins

Array Hash-Table Prefix-Sum

Problem Statement

Link - Problem 974

Question

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:

Solution

/*class Solution {
public:
    int subarraysDivByK(vector<int>& nums, int k) {
        std::ios::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);

        vector<int> prefixSum(nums.size(),0);
        prefixSum[0] =nums[0];
        for(int i = 1; i<nums.size(); i++)
            prefixSum[i] = prefixSum[i-1]+nums[i];
        int ans = 0;
        int temp;
        for(int i = 0;i<nums.size();i++)
        {
            for(int j = i; j<nums.size();j++)
            {
                temp = i==0?0:prefixSum[i-1];
                if((prefixSum[j]-temp)%k == 0)
                    ans++;
            }
        }
        return ans;
    }
};*/


class Solution {
public:
    int subarraysDivByK(vector<int>& nums, int k) {
        std::ios::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);

        unordered_map<int, int> map;
        map[0] = 1;
        int currsum = 0;
        int ans = 0;
        for(int i = 0; i < nums.size(); i++) {
            currsum += nums[i];
            int remainder = currsum % k;
            if(remainder < 0)
                remainder += k;
            ans += map[remainder];
            map[remainder]++;
        }
        return ans;
    }
};

Complexity Analysis

| Algorithm               | Time Complexity | Space Complexity |
| ----------------------- | --------------- | ---------------- |
| Prefix Sum with Hashmap | O(n)            | O(k)             |

Explanation

Intial Thoughts

The problem can be approached by considering all possible subarrays, calculating their sum, and checking if the sum is divisible by k. Another thought is to use prefix sums to efficiently calculate the sum of any subarray. We also need to think about how to efficiently store and look up the remainders when dividing by k. Key points to consider are: the use of prefix sums, iterating over all possible subarrays, and efficiently checking divisibility by k. Additionally, we should consider how to handle negative numbers and how to avoid counting empty subarrays. We also need to think about time complexity and how to optimize it.

Intuitive Analysis

To intuitively solve this problem, we can think of it as finding patterns in the data that allow us to quickly identify subarrays with sums divisible by k. We can use a hashmap to store the frequency of each remainder when dividing the sum by k. Key points to consider are: the hashmap can help us to avoid counting the same subarray multiple times, we should iterate over the array and for each element, calculate its contribution to the current sum, and then update the hashmap accordingly. We should also consider how to correctly handle the case when the remainder is negative. Furthermore, we should think about how to initialize the hashmap and how to return the correct count of subarrays with sums divisible by k. Additionally, we should analyze the time complexity of our approach and consider any potential optimizations.

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.


Similar Questions:

Title URL Difficulty
Subarray Sum Equals K https://leetcode.com/problems/subarray-sum-equals-k Medium
Make Sum Divisible by P https://leetcode.com/problems/make-sum-divisible-by-p Medium
Count Number of Bad Pairs https://leetcode.com/problems/count-number-of-bad-pairs Medium
Find the Divisibility Array of a String https://leetcode.com/problems/find-the-divisibility-array-of-a-string Medium
Count of Interesting Subarrays https://leetcode.com/problems/count-of-interesting-subarrays Medium
Maximum Subarray Sum With Length Divisible by K https://leetcode.com/problems/maximum-subarray-sum-with-length-divisible-by-k Medium