BlackFridaySale

Join the waitlist for an extra exclusive deal

Extra savings end in
00Days
13Hrs
09Mins
05Secs
Limited spots only

Count of Subarrays with Sum Divisible by K

25
0

Given an integer array nums and a positive integer k, return the number of non-empty contiguous subarrays whose sum is divisible by k.

Example 1

Input: nums = [3, 1, 4, 1], k = 3

Output: 3

Explanation: The valid subarrays are [3], [1, 4, 1], and [3, 1, 4, 1]. Their sums are 3, 6, and 9, respectively.

Example 2

Input: nums = [5, 10, -5, 20], k = 7

Output: 0

Explanation: No contiguous subarray has a sum divisible by 7.

Brute Force Approach

We generate all possible subarrays by trying every starting and ending index. For each starting index left, we reset the running sum to 0. Then we move the ending index right one position at a time, adding the new element to the running sum. After each addition, sum represents the total of the elements from left through right. If sum % k == 0, we count that subarray.

For example, starting at index 1 in [3, 1, 4, 1] generates [1], [1, 4], and [1, 4, 1]. The running sum starts at 1, becomes 5 after adding 4, and reaches 6 after adding the final 1. Only the last subarray qualifies when k = 3, because 6 is divisible by 3.

Approach

  1. Set the answer to 0.

  2. Choose each index left as the start of a subarray and reset sum to 0.

  3. For that start, try every ending index right from left to the end of the array.

  4. Add arr[right] to sum so it holds the total from left through right.

  5. If sum % k == 0, increment the answer by 1.

  6. Return the answer after checking every pair of starting and ending indices.

Dry Run

Subarrays with sum divisible by K brute force

Subarrays with sum divisible by K brute force

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Count subarrays whose sums are divisible by k, where k is positive.
long long subarraysDivByK(const vector<int>& nums, int k) {
const int n = static_cast<int>(nums.size());
// Use long long because the number of qualifying subarrays can be large.
long long answer = 0;
// Try each index as the start of a subarray.
for (int left = 0; left < n; ++left) {
// Start a fresh running sum whenever the starting index changes.
long long sum = 0;
// Start with the single element at left, then try every larger end index.
for (int right = left; right < n; ++right) {
// Reuse the previous sum and add just the newly included element.
// After this update, sum covers nums[left] through nums[right].
sum += nums[right];
// A remainder of zero means the sum is divisible by k.
// This check also works when the sum is zero or negative.
if (sum % k == 0) {
// Each pair of indices identifies exactly one subarray.
++answer;
}
}
}
// All nonempty subarrays have now been checked.
return answer;
}
};
int main() {
Solution sol;
vector<int> nums = {3, 1, 4, 1};
int k = 3;
// The qualifying subarrays are [3], [1, 4, 1], and [3, 1, 4, 1].
cout << sol.subarraysDivByK(nums, k) << '\n'; // Prints 3.
return 0;
}

Complexity Analysis

Time Complexity : O(N²). Each pair of endpoints is checked once, and extending the running sum takes constant time.

Space Complexity : O(1) auxiliary space. The algorithm stores only the indices, running sum, and answer.

Optimal Approach

Let prefix[i] be the sum of the first i elements, with prefix[0] = 0. The sum of the subarray from index left through index right is prefix[right + 1] - prefix[left].

This difference is divisible by k exactly when the two prefix sums leave the same remainder modulo k. For example, with k = 3, prefix sums 4 and 10 both leave remainder 1. Their difference is 6, so the subarray between them qualifies.

Store the remainders in a hash map called frequency. Each key is a remainder, and its value is the number of earlier prefixes with that remainder. If the current remainder has frequency 3, there are three valid starting positions for subarrays ending at the current index.

Start with frequency[0] = 1 so the empty prefix counts subarrays beginning at index 0. Add the current remainder’s frequency to the answer before incrementing it. That keeps the current prefix from matching itself and counting an empty subarray. If the remainder is negative, add k to bring it into the range 0 through k - 1.

Approach

  1. Initialize the prefix sum and answer to 0. Set frequency[0] = 1 to record the empty prefix before the array starts.

  2. Add the current element to the prefix sum and compute remainder = prefixSum % k.

  3. If the remainder is negative, add k so it falls between 0 and k - 1.

  4. Add the number of earlier prefixes with that remainder to the answer, then record the current prefix by incrementing its frequency.

  5. Return the answer after processing the array.

Dry Run

Subarrays with sums divisible by K optimal

Subarrays with sums divisible by K optimal

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Count subarrays whose sums are divisible by k, where k is positive.
long long subarraysDivByK(const vector<int>& nums, int k) {
// Map each remainder to the number of earlier prefixes that have it.
unordered_map<int, long long> frequency;
// The empty prefix has sum 0. Matching it counts a subarray
// that starts at index 0.
frequency[0] = 1;
// Use long long because both the running sum and the count can be large.
long long prefixSum = 0;
long long answer = 0;
for (int value : nums) {
// Extend the prefix to include the current element.
prefixSum += value;
// In C++, % can return a negative remainder for a negative sum.
// Adding k in that case keeps the remainder in [0, k - 1].
int remainder = prefixSum % k;
if (remainder < 0) {
remainder += k;
}
// Each matching prefix gives a distinct start for a subarray
// ending at the current element.
answer += frequency[remainder];
// Record the current prefix after counting. Matching it with
// itself would count an empty subarray.
++frequency[remainder];
}
// Every nonempty subarray was considered at its ending element.
return answer;
}
};
int main() {
Solution sol;
vector<int> nums = {3, 1, 4, 1};
int k = 3;
// The qualifying subarrays are [3], [1, 4, 1], and [3, 1, 4, 1].
cout << sol.subarraysDivByK(nums, k) << '\n'; // Prints 3.
return 0;
}

Complexity Analysis

Time Complexity : O(N) on average. Each element requires a constant number of hash map operations, each taking constant time on average.

Space Complexity : O(min(N + 1, K)). There are N + 1 prefixes including the empty prefix, and at most K distinct remainders.

Interview follow-up Questions

It represents the empty prefix before index 0. Whenever the current prefix has remainder 0, matching it with the empty prefix counts the subarray that starts at index 0.

HashingTCS NQTArrays

Read Similar Blogs

Comments0