Number of Divisible Triplet Sums
Number of Divisible Triplet Sums is a medium arrays & hashing problem solved with the hashing pattern.
The best approach, optimal (fix the last two, count remainders before them), runs in O(n²) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (try every triple) up.
Problem
You are given an integer array nums and a positive integer d.
Count the index triples (i, j, k) with i < j < k such that nums[i] + nums[j] + nums[k] is a multiple of d, and return that count.
Triples are told apart by their indexes, so equal values at different positions form different triples.
Examples
Example 1
- Input
nums = [2,5,1,4,3], d = 3- Output
4- Why
- Four index triples work: (0, 2, 4) gives 2 + 1 + 3 = 6, (0, 3, 4) gives 2 + 4 + 3 = 9, (1, 2, 4) gives 5 + 1 + 3 = 9 and (1, 3, 4) gives 5 + 4 + 3 = 12. All four sums are multiples of 3; the other six triples are not.
Example 2
- Input
nums = [4,4,4,4], d = 6- Output
4- Why
- Any three of the four elements add up to 12, which is a multiple of 6. There are 4 ways to choose three indexes out of four.
Example 3
- Input
nums = [1,2,6], d = 4- Output
0- Why
- The only triple is the whole array, and 1 + 2 + 6 = 9 is not a multiple of 4.
Constraints
3 <= nums.length <= 10001 <= nums[i] <= 10^91 <= d <= 10^9
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 30 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (try every triple) | O(n³) | O(1) |
| Optimal (fix the last two, count remainders before them) | O(n²) | O(n) |
1Brute force (try every triple)
O(n³)There are n * (n - 1) * (n - 2) / 6 triples, and each one is checked in constant time.O(1)Only the loop indexes and the counter.Check all ways to choose three indexes i < j < k with three nested loops and test whether the sum is a multiple of d. The sum can be as large as 3 * 10^9, so add the numbers as 64-bit values before taking the remainder.
- Set count = 0.
- For every i, every j > i and every k > j: if (nums[i] + nums[j] + nums[k]) % d == 0, add one to count.
- Return count.
class Solution {
public int divisibleTripletCount(int[] nums, int d) {
int n = nums.length, count = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
long sum = (long) nums[i] + nums[j] + nums[k];
if (sum % d == 0) count++;
}
}
}
return count;
}
}class Solution:
def divisibleTripletCount(self, nums: List[int], d: int) -> int:
n = len(nums)
count = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if (nums[i] + nums[j] + nums[k]) % d == 0:
count += 1
return countclass Solution {
public:
int divisibleTripletCount(vector<int>& nums, int d) {
int n = nums.size(), count = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
long long sum = (long long) nums[i] + nums[j] + nums[k];
if (sum % d == 0) count++;
}
}
}
return count;
}
};function divisibleTripletCount(nums, d) {
const n = nums.length;
let count = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
for (let k = j + 1; k < n; k++) {
if ((nums[i] + nums[j] + nums[k]) % d === 0) count++;
}
}
}
return count;
}2Optimal (fix the last two, count remainders before them)
O(n²)There are about n² / 2 pairs (j, k), each handled with one hash map lookup in expected constant time.O(n)The map holds at most one entry per element, so at most n remainders.Only remainders modulo d matter. Fix the middle index j and the last index k. Their two numbers leave remainder (nums[j] + nums[k]) % d, so the first number nums[i] must make up the rest: its remainder has to be need = (d - (nums[j] + nums[k]) % d) % d. If a hash map counts the remainders of all elements before j, the number of good i for this pair is a single lookup. Walk j from left to right; for each j, try every k after it, then add nums[j] % d to the map so it can serve as the first index for later middles. Every triple i < j < k is counted exactly once, at its own middle j and last k.
- Create an empty map seen from remainder to how many earlier elements have it, and set count = 0.
- For j = 0 to n - 1: for every k > j, compute need = (d - (nums[j] + nums[k]) % d) % d (in 64 bits) and add seen[need] to count.
- After the inner loop, increase seen[nums[j] % d] by one.
- Return count.
class Solution {
public int divisibleTripletCount(int[] nums, int d) {
Map<Integer, Integer> seen = new HashMap<>();
int n = nums.length, count = 0;
for (int j = 0; j < n; j++) {
for (int k = j + 1; k < n; k++) {
int need = (int) ((d - ((long) nums[j] + nums[k]) % d) % d);
count += seen.getOrDefault(need, 0);
}
seen.merge(nums[j] % d, 1, Integer::sum);
}
return count;
}
}class Solution:
def divisibleTripletCount(self, nums: List[int], d: int) -> int:
seen = defaultdict(int)
n = len(nums)
count = 0
for j in range(n):
for k in range(j + 1, n):
need = (d - (nums[j] + nums[k]) % d) % d
count += seen.get(need, 0)
seen[nums[j] % d] += 1
return countclass Solution {
public:
int divisibleTripletCount(vector<int>& nums, int d) {
unordered_map<int, int> seen;
int n = nums.size(), count = 0;
for (int j = 0; j < n; j++) {
for (int k = j + 1; k < n; k++) {
int need = (int) ((d - ((long long) nums[j] + nums[k]) % d) % d);
auto it = seen.find(need);
if (it != seen.end()) count += it->second;
}
seen[nums[j] % d]++;
}
return count;
}
};function divisibleTripletCount(nums, d) {
const seen = new Map();
const n = nums.length;
let count = 0;
for (let j = 0; j < n; j++) {
for (let k = j + 1; k < n; k++) {
const need = (d - (nums[j] + nums[k]) % d) % d;
count += seen.get(need) || 0;
}
const r = nums[j] % d;
seen.set(r, (seen.get(r) || 0) + 1);
}
return count;
}Edge cases to test
- d = 1: every triple counts, so the answer is n * (n - 1) * (n - 2) / 6
- Exactly three elements: the answer is 0 or 1
- Large values: a sum of three numbers up to 10^9 does not fit in a 32-bit int, so add in 64 bits or reduce each value modulo d first
- d larger than every possible sum: no triple can reach a positive multiple of d, so the answer is 0
- Many equal values or equal remainders: the same remainder must be counted once per index, not once per value
- The answer can reach about 1.66 * 10^8 (all triples of 1000 elements), which still fits in an int
Hints
Hint 1
Only the remainders modulo d matter: a + b + c is divisible by d exactly when (a % d + b % d + c % d) % d is 0.
Hint 2
Fix the middle index j and the last index k. Which remainder must nums[i] have, for an index i before j?
Hint 3
Keep a count of the remainders of nums[0 .. j - 1] in a hash map. Then each pair (j, k) adds the count of the remainder it needs.
FAQ
What is the best time complexity for Number of Divisible Triplet Sums?
Optimal (fix the last two, count remainders before them) runs in O(n²) time and O(n) extra space. There are about n² / 2 pairs (j, k), each handled with one hash map lookup in expected constant time.
Which pattern does Number of Divisible Triplet Sums use?
It is a arrays & hashing problem that uses the hashing pattern. Other problems with the same pattern: Group Anagrams, First Unique Character in a String, Number of Matching Subsequences.
Is there a brute force solution for Number of Divisible Triplet Sums?
Yes. Brute force (try every triple) takes O(n³) time and O(1) space. Check all ways to choose three indexes i < j < k with three nested loops and test whether the sum is a multiple of d.
Which edge cases should I test for Number of Divisible Triplet Sums?
d = 1: every triple counts, so the answer is n (n - 1) (n - 2) / 6; Exactly three elements: the answer is 0 or 1; Large values: a sum of three numbers up to 10^9 does not fit in a 32-bit int, so add in 64 bits or reduce each value modulo d first; d larger than every possible sum: no triple can reach a positive multiple of d, so the answer is 0; Many equal values or equal remainders: the same remainder must be counted once per index, not once per value; The answer can reach about 1.66 10^8 (all triples of 1000 elements), which still fits in an int.