Number of Divisible Triplet Sums
Medium
Topics
Given a 0-indexed integer array nums and an integer k, return the number of index triplets (i, j, l) with i < j < l such that nums[i] + nums[j] + nums[l] is divisible by k.
The divisor is called k here because that is what the judge names the second argument; LeetCode calls it d.
Example 1
Input: nums = [3,3,4,7,8], k = 5 Output: 3 Explanation: The triplets are (0,1,2) summing to 10, (0,2,4) summing to 15 and (1,2,4) summing to 15.
Example 2
Input: nums = [3,3,3,3], k = 3 Output: 4 Explanation: Every triplet sums to 9. There are four ways to pick three of the four indices.
Example 3
Input: nums = [3,3,3,3], k = 6 Output: 0 Explanation: Every triplet sums to 9, which leaves remainder 3.
Constraints
- 3 <= nums.length <= 1000
- 1 <= nums[i] <= 10^9
- 1 <= k <= 10^9
Editorial — intuition, approach, complexity and pitfalls
Intuition
Three nested loops test every triplet and that is n³, too slow at a thousand elements. The way out is the one that works for two-sum: fix part of the triplet and let a lookup supply the rest.
Divisibility is the useful structure. Whether a sum is divisible by k depends only on the three remainders, not the values, so the problem lives in the world of residues mod k. Once two of the three are fixed, the third residue is forced: it must be (-(ra + rb)) mod k.
So fix the largest index of the triplet and ask how many pairs before it have the required residue. Counting pairs by residue as the scan proceeds makes that a single lookup, which brings the whole thing down to n².
Approach
- Keep a count of how many pairs seen so far have each residue mod
k. - Scan an index
lfrom left to right. The triplets ending atlare exactly the recorded pairs whose residue completesnums[l]to a multiple ofk, so add the count for residue(k - nums[l] % k) % k. - After counting, fold index
linto the pair table: for every earlier indexj, record the residue ofnums[j] + nums[l]. This keeps the table holding exactly the pairs with both indices below the nextl. - The inner loop is what makes this quadratic rather than cubic, and the ordering is what guarantees
i < j < lwithout any explicit check.
Walkthrough
nums = [3,3,4,7,8], k = 5
residues: 3, 3, 4, 2, 3
l=0 need residue 2, pairs table empty count 0
add no pairs (no earlier index)
l=1 need residue 2, table empty count 0
add pair (0,1): (3+3)%5 = 1 {1:1}
l=2 need (5-4%5)%5 = 1, table has 1 -> 1 count 1 [(0,1,2)]
add (0,2): (3+4)%5=2 (1,2): 2 {1:1, 2:2}
l=3 need (5-2)%5 = 3, table has none count 1
add (0,3): (3+7)%5=0 (1,3): 0 (2,3): (4+7)%5=1
{0:2, 1:2, 2:2}
l=4 need (5-3)%5 = 2, table has 2 -> 2 count 3 [(0,2,4),(1,2,4)]
answer 3Complexity
- Time — O(n^2): the outer scan is linear and each step folds in up to n pairs. The pair table turns the search for the third element into one lookup.
- Space — O(min(n^2, k)): one counter per distinct pair residue; there are at most n²/2 pairs and at most k residues.
Common Pitfalls
- Writing the needed residue as
-nums[l] % k. In languages where the modulo of a negative number is negative, that produces a key that is never in the table. The extra(k - x % k) % kwrapping is what keeps it non-negative, and the outer% kmatters whennums[l]is already a multiple ofk. - Recording index
l’s pairs before counting the triplets that end at it, which letslappear twice in one triplet. - Counting unordered value triplets instead of index triplets. Example 2 answers 4 because the four indices give four triplets, even though the values are identical.
- Assuming all values are distinct and deduplicating. Repeats are allowed and each index counts separately.
Full Solution — all languages
class Solution:
def divisibleTripletCount(self, nums, k):
pair_residues = {}
total = 0
for l in range(len(nums)):
need = (k - nums[l] % k) % k
total += pair_residues.get(need, 0)
for j in range(l):
r = (nums[j] + nums[l]) % k
pair_residues[r] = pair_residues.get(r, 0) + 1
return totalimport java.util.*;
class Solution {
public int divisibleTripletCount(int[] nums, int k) {
Map<Long, Long> pairResidues = new HashMap<>();
long total = 0;
for (int l = 0; l < nums.length; l++) {
long need = ((long) k - nums[l] % k) % k;
total += pairResidues.getOrDefault(need, 0L);
for (int j = 0; j < l; j++) {
long r = ((long) nums[j] + nums[l]) % k;
pairResidues.merge(r, 1L, Long::sum);
}
}
return (int) total;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int divisibleTripletCount(vector<int>& nums, int k) {
unordered_map<long long, long long> pairResidues;
long long total = 0;
for (size_t l = 0; l < nums.size(); l++) {
long long need = ((long long)k - nums[l] % k) % k;
auto it = pairResidues.find(need);
if (it != pairResidues.end()) total += it->second;
for (size_t j = 0; j < l; j++) {
long long r = ((long long)nums[j] + nums[l]) % k;
pairResidues[r]++;
}
}
return (int)total;
}
};/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/ var divisibleTripletCount = function(nums, k) {
const pairResidues = new Map();
let total = 0;
for (let l = 0; l < nums.length; l++) {
const need = (k - nums[l] % k) % k;
total += pairResidues.get(need) || 0;
for (let j = 0; j < l; j++) {
const r = (nums[j] + nums[l]) % k;
pairResidues.set(r, (pairResidues.get(r) || 0) + 1);
}
}
return total;
};