Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum which is divisible by n in JavaScript
We need to write a JavaScript function that counts the number of contiguous subarrays whose sum is divisible by a given number. This problem uses modular arithmetic and prefix sums for an efficient solution.
Problem Statement
Given an array of numbers and a divisor, find how many contiguous subarrays have a sum divisible by the divisor.
Input: arr = [4, 5, 0, -2, -3, 1], num = 5 Output: 7
Output Explanation
There are 7 subarrays with a sum divisible by 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Algorithm Approach
The solution uses prefix sums and modular arithmetic. If two prefix sums have the same remainder when divided by the target number, the subarray between them has a sum divisible by that number.
Example Implementation
const arr = [4, 5, 0, -2, -3, 1];
const num = 5;
const divisibleSum = (arr = [], num = 1) => {
const map = {};
let sum = 0;
// Count remainders of prefix sums
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
const key = ((sum % num) + num) % num; // Handle negative numbers
map[key] = (map[key] || 0) + 1;
}
let count = 0;
// Count pairs with same remainder
for (let i = 0; i < num; i++) {
if (map[i] > 1) {
count += (map[i] * (map[i] - 1)) / 2;
}
}
// Add subarrays starting from index 0 with sum divisible by num
return count + (map[0] || 0);
};
console.log(divisibleSum(arr, num));
7
How It Works
The algorithm works in three steps:
- Track prefix sum remainders: For each element, calculate the running sum and its remainder when divided by the target number
- Count remainder pairs: If two positions have the same remainder, the subarray between them is divisible by the target
- Add zero remainders: Prefix sums with remainder 0 represent subarrays divisible by the target starting from index 0
Time Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Brute Force | O(n²) | O(1) |
| Prefix Sum + HashMap | O(n) | O(n) |
Conclusion
This efficient solution uses modular arithmetic and prefix sums to count divisible subarrays in linear time. The key insight is that subarrays between positions with equal remainder modulo n have sums divisible by n.
