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]
.
Return _the number ofsingle divisor triplets of _nums
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
3 <= nums.length <= 10^5
1 <= nums[i] <= 100
Solution
Method 1 – Counting with Frequency Array
Intuition
Since all numbers are between 1 and 100, we can count the frequency of each number and enumerate all possible triplets of values (a, b, c). For each triplet, we check if the sum is divisible by exactly one of a, b, or c, and count the number of index permutations using the frequencies.
Approach
- Count the frequency of each number in
nums
(from 1 to 100). - For all ordered triplets (a, b, c) with possible repetitions, check:
- All indices are distinct (i, j, k), but values can repeat.
- For each (a, b, c), compute
s = a + b + c
. - Count how many of (a, b, c) divide
s
. - If exactly one divides, add the number of index permutations for (a, b, c) to the answer.
- For (a, b, c) all different, count = freq[a] * freq[b] * freq[c] * 6. For two equal, count = freq[a] * (freq[a]-1) * freq[b] * 3 (choose which two are equal). For all equal, skip (since s is always divisible by all three).
- Return the total count.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(100^3) = O(1)
, since the value range is fixed and small. Counting frequencies isO(n)
. - 🧺 Space complexity:
O(1)
, for the frequency array (size 101).