Number of Unequal Triplets in Array - Problem

You are given a 0-indexed array of positive integers nums. Find the number of triplets (i, j, k) that meet the following conditions:

  • 0 <= i < j < k < nums.length
  • nums[i], nums[j], and nums[k] are pairwise distinct.
  • In other words, nums[i] != nums[j], nums[i] != nums[k], and nums[j] != nums[k].

Return the number of triplets that meet the conditions.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,4,2,4,3]
Output: 3
💡 Note: Valid triplets are (0,2,4), (1,2,4), (2,3,4) with values (4,2,3). All have distinct values.
Example 2 — No Valid Triplets
$ Input: nums = [1,1,1,1,1]
Output: 0
💡 Note: All elements are the same, so no triplet can have pairwise distinct values.
Example 3 — All Unique
$ Input: nums = [1,2,3]
Output: 1
💡 Note: Only one triplet (0,1,2) with values (1,2,3), all distinct.

Constraints

  • 3 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Number of Unequal Triplets in Array INPUT nums = [4, 4, 2, 4, 3] 4 i=0 4 i=1 2 i=2 4 i=3 3 i=4 Unique Values: 4 count:3 2 count:1 3 count:1 Find triplets (i, j, k) where i < j < k and all values are pairwise distinct Array Length: 5 3 unique values: {4, 2, 3} ALGORITHM STEPS 1 Count Frequencies Build frequency map of values {4:3, 2:1, 3:1} 2 Use Counting Method Track left and right counts for each unique value 3 Calculate Triplets For each value v: triplets += left * cnt * right 4 Iterate Values Process each unique value, update left count Calculation: v=4: left=0, cnt=3, right=2 v=2: left=3, cnt=1, right=1 v=3: left=4, cnt=1, right=0 Total: 0 + 3 + 0 = 3 FINAL RESULT Output: 3 Valid Triplets Found: Triplet 1: (0,2,4): nums[4,2,3] - OK Triplet 2: (1,2,4): nums[4,2,3] - OK Triplet 3: (2,3,4): nums[2,4,3] - OK Complexity: Time: O(n) Space: O(n) Key Insight: Instead of checking all O(n^3) triplets, use counting: for each unique value v, count elements before (left) and after (right) all occurrences of v. Triplets with v as middle = left * count(v) * right. Sum for all values. This reduces complexity from O(n^3) to O(n) by leveraging frequency counts and multiplication principle. TutorialsPoint - Number of Unequal Triplets in Array | Optimal Solution
Asked in
Google 15 Amazon 10
8.5K Views
Medium Frequency
~15 min Avg. Time
245 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