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.
1#include <vector>
2#include <unordered_map>
3#include <iostream>
4
5int subarraysDivByK(std::vector<int>& nums, int k) {
6 std::unordered_map<int, int> modCount;
7 modCount[0] = 1;
8 int count = 0, cumSum = 0;
9 for (int num : nums) {
10 cumSum += num;
11 int mod = ((cumSum % k) + k) % k;
12 count += modCount[mod];
13 modCount[mod]++;
14 }
15 return count;
16}
17
18int main() {
19 std::vector<int> nums = {4, 5, 0, -2, -3, 1};
20 int k = 5;
21 std::cout << "Number of subarrays divisible by " << k << ": " << subarraysDivByK(nums, k) << std::endl;
22 return 0;
23}
In this C++ implementation, an unordered_map is used to store the frequency of each remainder when the cumulative sum is taken modulo k. This map is initialized with a zero frequency of one to account for subarrays with sum divisible by k. We iterate through the array, and for each element, we calculate the cumulative sum and its corresponding modulo. The count of subarrays is incremented by the frequency of the current modulo seen so far.
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 Python implementation uses a straightforward two-loop nested structure to evaluate each possible subarray. For each subarray, the cumulative sum is calculated, and it increments the counter if this sum is divisible by k.