Number of Divisible Triplet Sums Problem
#2964
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2964.
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.
Example 1:
Input: nums = [3,3,4,7,8], d = 5
Output: 3
Explanation: The triplets which are divisible by 5 are: (0, 1, 2), (0, 2, 4), (1, 2, 4).
It can be shown that no other triplet is divisible by 5. Hence, the answer is 3.
Example 2:
Input: nums = [3,3,3,3], d = 3
Output: 4
Explanation: Any triplet chosen here has a sum of 9, which is divisible by 3. Hence, the answer is the total number of triplets which is 4.
Example 3:
Input: nums = [3,3,3,3], d = 6
Output: 0
Explanation: Any triplet chosen here has a sum of 9, which is not divisible by 6. Hence, the answer is 0.
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 10^91 <= d <= 10^9
Solution
Approach: Hash Table + Enumeration
Fix the two later indices j < k and count how many earlier elements nums[i] complete the sum. For the sum to be divisible by d, the remainder of nums[i] must equal (d - (nums[j] + nums[k]) % d) % d. A hash table cnt stores how many of the elements before j have each remainder, so each pair (j, k) adds one lookup. After all k are processed for a given j, the remainder of nums[j] is added to the table.
The time complexity is O(n^2) and the space complexity is O(n), where n is the length of nums.
from collections import defaultdict
class Solution:
def divisibleTripletCount(self, nums: List[int], d: int) -> int:
cnt = defaultdict(int)
ans, n = 0, len(nums)
for j in range(n):
for k in range(j + 1, n):
x = (d - (nums[j] + nums[k]) % d) % d
ans += cnt[x]
cnt[nums[j] % d] += 1
return ans