#2475

Number of Unequal Triplets in Array

Easy
ArrayHash TableSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n³)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of checking all triplets, we can count the occurrences of each number and use combinatorial math to find the number of distinct triplets. This is more efficient and leverages the properties of combinations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the frequency of each distinct number in the array using a hashmap.
  2. 2Step 2: Calculate the total number of triplets that can be formed from the array using the formula nC3 = n! / (3!(n-3)!).
  3. 3Step 3: Subtract the number of triplets that can be formed with the same numbers (using the frequencies from the hashmap).
  4. 4Step 4: Return the final count of distinct triplets.
solution.py14 lines
1# Full working Python code
2
3def countTriplets(nums):
4    from collections import Counter
5    freq = Counter(nums)
6    totalTriplets = len(nums) * (len(nums) - 1) * (len(nums) - 2) // 6
7    sameTriplets = 0
8    for count in freq.values():
9        if count >= 3:
10            sameTriplets += count * (count - 1) * (count - 2) // 6
11    return totalTriplets - sameTriplets
12
13# Example usage
14print(countTriplets([4,4,2,4,3]))  # Output: 3

Complexity note: The time complexity is O(n) because we traverse the array once to count frequencies and then again to calculate the triplets. The space complexity is O(n) due to the hashmap storing the frequencies of distinct numbers.

  • 1Count distinct numbers efficiently using a hashmap.
  • 2Use combinatorial math to calculate triplet combinations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.