Problem Description
Given an array of positive integers, count the number of ordered triplets (i, j, k) of distinct indices such that the sum of the three elements is divisible by exactly one of the three numbers. Note that even if the array contains duplicate numbers, the triplets must use three distinct indices. The answer should count all orderings (i.e. permutations) of a valid combination.
Key Insights
- The values in nums are bounded by 100 while the array length can be up to 10^5. This allows us to use a frequency table and iterate over possible values (1 to 100) instead of iterating over indices directly.
- For each combination of numbers (a, b, c) from the frequency table, compute the sum (S = a + b + c) and check if S is divisible by exactly one of a, b, or c.
- When counting triplets, careful handling is required for cases where the selected numbers are distinct, two are equal, or all three are equal. Since the problem asks for ordered triplets, every unordered selection of 3 distinct indices converts to 6 ordered triplets.
- Using combinatorics (e.g. freq choose 2, freq choose 3) for duplicates and then multiplying by 6 (or the appropriate factor) gives the correct count.
Space and Time Complexity
Time Complexity: O(100^3) which is O(1e6) operations in the worst case (negligible compared to 10^5).
Space Complexity: O(101) or O(1) extra space for the frequency table.
Solution
The solution uses a frequency array of size 101 (since nums[i] is in [1, 100]) to count occurrences. Then, by iterating over all triple combinations (a, b, c) with a ≤ b ≤ c, we check if the sum S = a + b + c is divisible by exactly one of a, b, or c.
For each valid combination, we calculate the number of unordered ways to pick indices based on the frequency counts:
- All numbers distinct: ways = freq[a] * freq[b] * freq[c]
- Two identical and one different: ways = C(freq[x], 2) * freq[y] (where x is the repeated number)
- All equal: ways = C(freq[a], 3)
Since every unordered triplet of indices gives rise to 6 ordered triplets, we multiply the computed ways by 6 and add it to the answer.