Number of Unequal Triplets in Array - Problem
Number of Unequal Triplets in Array

You're given an array of positive integers, and your task is to find all the unique triplets where each element in the triplet is different from the others.

More specifically, you need to count triplets (i, j, k) where:
• The indices satisfy 0 ≤ i < j < k < nums.length
• All three values are pairwise distinct: nums[i] ≠ nums[j] ≠ nums[k] ≠ nums[i]

Example: In array [4, 4, 2, 4, 3], the triplet at indices (2, 4, 1) becomes (2, 3, 4) in terms of values - all different!

Return the total count of such valid triplets.

Input & Output

example_1.py — Basic Case
$ Input: [4,4,2,4,3]
Output: 3
💡 Note: The valid triplets are: (0,2,4) with values (4,2,3), (1,2,4) with values (4,2,3), (3,2,4) with values (4,2,3). All have distinct values.
example_2.py — All Same Values
$ Input: [1,1,1]
Output: 0
💡 Note: No valid triplets exist since all values are the same (1,1,1), violating the distinct requirement.
example_3.py — All Different Values
$ Input: [1,3,2,5,4]
Output: 10
💡 Note: Since all values are unique, every possible triplet of indices forms a valid solution. Total = C(5,3) = 10 triplets.

Visualization

Tap to expand
🍽️ Restaurant Groups Analogy🍝Italian (3)🍜Chinese (1)🌮Mexican (1)Step 1: Count by PreferenceArray: [Italian, Italian, Chinese, Italian, Mexican]Frequency: Italian×3, Chinese×1, Mexican×1We need groups with all different cuisinesStep 2: Form Mixed GroupsEach dinner group needs:1 Italian lover × 1 Chinese lover × 1 Mexican loverTotal combinations: 3 × 1 × 1 = 3 groupsConnection to Array Problem:🔗 Each cuisine type = unique array value🔗 People count = frequency of that value🔗 Mixed dinner group = triplet with distinct values🎯 Multiply frequencies instead of checking every combination!
Understanding the Visualization
1
Count People by Cuisine
First, count how many people like Italian (3), Chinese (1), Mexican (1)
2
Form Mixed Groups
To form groups with all different preferences, pick 1 from each cuisine type
3
Calculate Combinations
Total groups = 3 × 1 × 1 = 3 different dinner groups possible
Key Takeaway
🎯 Key Insight: Use the multiplication principle from combinatorics - if you have groups of different sizes, multiply their sizes to get total combinations. This transforms an O(n³) problem into O(n + k³) where k is unique values!

Time & Space Complexity

Time Complexity
⏱️
O(n + k³)

O(n) to build frequency map + O(k³) to check all combinations of k unique values

n
2n
Linear Growth
Space Complexity
O(k)

Space for frequency map storing k unique values

n
2n
Linear Space

Constraints

  • 3 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000
  • Array has at least 3 elements
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.7K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen