Number of Divisible Triplet Sums

Medium

Topics
ArrayHash Table

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

3031427384
one qualifying triplet
A triplet is three positions with increasing indices, not three distinct values — so repeated numbers still give separate triplets. The shaded one is indices (0, 1, 2), summing to 10, which divides by 5. 3 triplets in this array qualify.
Cells are the array values; the small numbers underneath are indices.
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

30313233
one qualifying triplet
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

30313233
No triplet in this array sums to a multiple of 6, so the answer is 0.
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

  1. Keep a count of how many pairs seen so far have each residue mod k.
  2. Scan an index l from left to right. The triplets ending at l are exactly the recorded pairs whose residue completes nums[l] to a multiple of k, so add the count for residue (k - nums[l] % k) % k.
  3. After counting, fold index l into the pair table: for every earlier index j, record the residue of nums[j] + nums[l]. This keeps the table holding exactly the pairs with both indices below the next l.
  4. The inner loop is what makes this quadratic rather than cubic, and the ordering is what guarantees i < j < l without 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 3

Complexity

  • 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) % k wrapping is what keeps it non-negative, and the outer % k matters when nums[l] is already a multiple of k.
  • Recording index l’s pairs before counting the triplets that end at it, which lets l appear 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 total
SensAI
Beta
Tap the mic to stop voice mode