Number of Single Divisor Triplets — LeetCode 2198 Python Solution
- Problem
- #2198
- Pattern
- Math and Number Theory
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given a 0-indexed array of positive integers nums. A triplet of three distinct indices (i, j, k) is called a single divisor triplet of nums if nums[i] + nums[j] + nums[k] is divisible by exactly one of nums[i], nums[j], or nums[k].
Example
- Input
- nums = [4,6,7,3,2]
- Output
- 12
- Explanation
- The triplets (0, 3, 4), (0, 4, 3), (3, 0, 4), (3, 4, 0), (4, 0, 3), and (4, 3, 0) have the values of [4, 3, 2] (or a permutation of [4, 3, 2]).
Python solution
class Solution:
def singleDivisorTriplet(self, nums: List[int]) -> int:
cnt = Counter(nums)
ans = 0
for a, x in cnt.items():
for b, y in cnt.items():
for c, z in cnt.items():
s = a + b + c
if sum(s % v == 0 for v in (a, b, c)) == 1:
if a == b:
ans += x * (x - 1) * z
elif a == c:
ans += x * (x - 1) * y
elif b == c:
ans += x * y * (y - 1)
else:
ans += x * y * z
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(M^3) |
| Space | O(M) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2198. Number of Single Divisor Triplets is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2198. Number of Single Divisor Triplets?
- LeetCode 2198. Number of Single Divisor Triplets is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2198. Number of Single Divisor Triplets?
- The Python solution on this page runs in O(M^3).
- What is the space complexity of LeetCode 2198. Number of Single Divisor Triplets?
- The Python solution on this page uses O(M) auxiliary space.
- What topics does LeetCode 2198. Number of Single Divisor Triplets cover?
- LeetCode 2198. Number of Single Divisor Triplets is tagged Math on LeetCode.
- Is LeetCode 2198. Number of Single Divisor Triplets a premium problem?
- Yes. LeetCode 2198. Number of Single Divisor Triplets is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.