Sponsored
Sponsored
This approach leverages prefix sums and the properties of modular arithmetic to efficiently count subarrays whose sums are divisible by k. By maintaining a hashmap (or dictionary) that keeps track of the frequency of each remainder observed when computing prefix sums modulo k, we can determine how many valid subarrays end at each position in the array.
For any position in the array, if we have the same remainder as a previously computed prefix sum, it indicates that the subarray between the two indices is divisible by k.
Time Complexity: O(n), where n is the number of elements in the array, as we iterate over the array once.
Space Complexity: O(k), where k is the number of different remainders we track in our modCount array.
1function subarraysDivByK(nums, k) {
2 let modCount = {0: 1};
3 let count = 0, cumSum = 0;
4 for (let num of nums) {
5 cumSum += num;
6 let mod = (cumSum % k + k) % k;
7 count += modCount[mod] || 0;
8 modCount[mod] = (modCount[mod] || 0) + 1;
9 }
10 return count;
11}
12
13const nums = [4, 5, 0, -2, -3, 1];
14const k = 5;
15console.log(`Number of subarrays divisible by ${k}: ${subarraysDivByK(nums, k)}`);
This JavaScript solution maintains a modCount object to count frequencies of each remainder seen during cumulative sum processing. It begins with an entry for remainder 0 to include subarrays starting from the first element. Iteratively updating the cumulative sum and its remainder, the tally of subarrays increases whenever current remainders are found in the map.
The brute force approach involves checking all possible subarrays to find those whose sum is divisible by k. This method is less efficient and should be used primarily for small inputs due to its higher time complexity. We iterate over all subarray starting points and compute the sum for all possible ending positions, counting subarrays that meet the criteria.
Time Complexity: O(n^2), where n is the number of elements in the array (due to double loop).
Space Complexity: O(1), as only integer counters and accumulators are used.
This brute force Java solution explores all subarrays by using a nested loop structure. It calculates the subarray sum from start to each possible endpoint, assessing divisibility by k, and increments a counter for each valid sum.