Number of Divisible Triplet Sums — LeetCode 2964 Python Solution
- Problem
- #2964
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- 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).
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2964. Number of Divisible Triplet Sums is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2964. Number of Divisible Triplet Sums?
- LeetCode 2964. Number of Divisible Triplet Sums is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2964. Number of Divisible Triplet Sums?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 2964. Number of Divisible Triplet Sums?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2964. Number of Divisible Triplet Sums cover?
- LeetCode 2964. Number of Divisible Triplet Sums is tagged Array and Hash Table on LeetCode.
- Is LeetCode 2964. Number of Divisible Triplet Sums a premium problem?
- Yes. LeetCode 2964. Number of Divisible Triplet Sums is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.