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: 4
💡 Note: Valid triplets: (0,3,6 doesn't exist), (0,1,2) sum=3, (0,3,6 doesn't exist), (1,2,3) sum=6, (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 SumsInput: nums = [3,3,4,7,8], d = 53347801234Find triplets where sum % 5 == 0:(0,1,2): 3+3+4=10(0,2,4): 3+4+8=15(1,2,4): 3+4+8=1510 % 5 = 0 ✓15 % 5 = 0 ✓15 % 5 = 0 ✓Output: 3 valid triplets
Asked in
Google 25 Amazon 18 Facebook 12
28.2K 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