Number of Divisible Triplet Sums - Problem

Given a 0-indexed integer array nums and an integer d, return the number of triplets (i, j, k) such that i < j < k and (nums[i] + nums[j] + nums[k]) % d == 0.

A triplet is a set of three indices where the sum of the elements at those indices is divisible by d.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,3,4,7,8], d = 5
Output: 3
💡 Note: Valid triplets are: (0,1,2) with sum 3+3+4=10 (divisible by 5), (0,2,4) with sum 3+4+8=15 (divisible by 5), and (1,2,4) with sum 3+4+8=15 (divisible by 5)
Example 2 — All Same Remainder
$ Input: nums = [0,1,2,3,4,5], d = 3
Output: 8
💡 Note: Valid triplets: (0,1,2) sum=3, (0,1,5) sum=6, (0,2,4) sum=6, (0,4,5) sum=9, (1,2,3) sum=6, (1,3,5) sum=9, (2,3,4) sum=9, (3,4,5) sum=12 - all divisible by 3
Example 3 — No Valid Triplets
$ Input: nums = [1,2,4], d = 3
Output: 0
💡 Note: Only one triplet (0,1,2) with sum 1+2+4=7, and 7%3=1≠0, so no valid triplets

Constraints

  • 3 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 1000
  • 1 ≤ d ≤ 5

Visualization

Tap to expand
Number of Divisible Triplet Sums INPUT nums array: 3 i=0 3 i=1 4 i=2 7 i=3 8 i=4 Remainders (mod 5): 3 3 4 2 3 nums = [3,3,4,7,8] d = 5 Find triplets where sum % 5 == 0 with i < j < k ALGORITHM STEPS 1 Build Remainder Map Count freq of nums[i] % d 2 Iterate Pairs (i,j) For each pair, calc target rem 3 Find Third Element target = (d - (r_i+r_j)%d) % d 4 Count Valid Triplets Add count from hash map Remainder Frequency Map: rem 2: 1 rem 3: 3 rem 4: 1 Check: (3+3+4)%5=0, (3+4+8)%5=0... Remainders: 3+3+4=10, 10%5=0 FINAL RESULT Valid Triplets Found: (0,2,4): nums[0]+nums[2]+nums[4] 3 + 4 + 8 = 15 (15%5=0) OK (0,1,2): nums[0]+nums[1]+nums[2] 3 + 3 + 4 = 10 (10%5=0) OK (1,2,4): nums[1]+nums[2]+nums[4] 3 + 4 + 8 = 15 (15%5=0) OK Output: 3 3 triplets satisfy the divisibility condition Key Insight: Use a hash map to track remainder frequencies. For each pair (i,j), compute the required third remainder: target_remainder = (d - (nums[i] + nums[j]) % d) % d This reduces lookup from O(n) to O(1), optimizing the brute force O(n^3) approach to O(n^2) with O(n) space. TutorialsPoint - Number of Divisible Triplet Sums | Hash Map - Remainder Frequency Approach
Asked in
Google 25 Amazon 18 Facebook 12
28.3K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen