Number of Divisible Triplet Sums - Problem

You're given a 0-indexed integer array nums and an integer d. Your task is to find how many triplets of indices (i, j, k) exist such that:

  • i < j < k (indices must be in ascending order)
  • (nums[i] + nums[j] + nums[k]) % d == 0 (sum is divisible by d)

Think of this as finding special combinations of three numbers whose sum has a specific mathematical property. For example, if nums = [3, 3, 4, 7, 8] and d = 5, the triplet at indices (0, 1, 2) gives us 3 + 3 + 4 = 10, and 10 % 5 = 0, so this counts as a valid triplet.

Goal: Return the total count of such valid triplets.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [3, 3, 4, 7, 8], d = 5
โ€บ Output: 2
๐Ÿ’ก Note: Valid triplets are: (0,1,2) with sum 3+3+4=10, and (0,2,4) with sum 3+4+8=15. Both 10%5=0 and 15%5=0.
example_2.py โ€” No Valid Triplets
$ Input: nums = [1, 2, 3], d = 4
โ€บ Output: 0
๐Ÿ’ก Note: Only one possible triplet (0,1,2) with sum 1+2+3=6. Since 6%4=2โ‰ 0, there are no valid triplets.
example_3.py โ€” All Elements Same
$ Input: nums = [2, 2, 2, 2, 2], d = 3
โ€บ Output: 10
๐Ÿ’ก Note: Each triplet has sum 2+2+2=6, and 6%3=0. With 5 elements, there are C(5,3) = 10 possible triplets, all valid.

Constraints

  • 3 โ‰ค nums.length โ‰ค 1000
  • -109 โ‰ค nums[i] โ‰ค 109
  • 1 โ‰ค d โ‰ค 109
  • Important: Array indices must satisfy i < j < k

Visualization

Tap to expand
Divisible Triplet Sums: Modular Arithmetic VisualizationRemainder 0Count: nโ‚€Remainder 1Count: nโ‚Remainder 2Count: nโ‚‚... (up to d-1)Valid Triplet Patternsโ€ข Pattern 1: (0, 0, 0) โ†’ Choose 3 from remainder-0 group โ†’ C(nโ‚€, 3)โ€ข Pattern 2: (0, i, d-i) โ†’ One from 0-group, pairs from complementary groupsโ€ข Pattern 3: (i, j, k) where i+j+k โ‰ก 0 (mod d) โ†’ All different remaindersCombinatorial CalculationFor Pattern 1: C(nโ‚€, 3) = nโ‚€ ร— (nโ‚€-1) ร— (nโ‚€-2) / 6For Pattern 2 & 3: Multiply counts from each remainder group
Understanding the Visualization
1
Badge Assignment
Each number gets a 'remainder badge' showing its value mod d
2
Compatibility Rules
Three badges are compatible if their sum equals 0 mod d
3
Count Valid Groups
Use combinatorics to count all possible compatible triplets
4
Sum Results
Total all valid groupings from different badge combinations
Key Takeaway
๐ŸŽฏ Key Insight: By working with remainders instead of actual values, we transform a complex triplet-finding problem into a simple counting problem using modular arithmetic properties.
Asked in
Google 42 Amazon 35 Meta 28 Microsoft 31 Apple 18
28.5K Views
Medium-High Frequency
~25 min Avg. Time
1.3K 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