Leetcode 2475. Number of Unequal Triplets in Array
You are given a 0-indexed array of positive integers nums
. A triplet of indices (i, j, k)
is called unequal if:
0 <= i < j < k < nums.length, and
nums[i], nums[j], and nums[k] are pairwise distinct.
Return the number of unequal triplets in nums
.
Can the array contain duplicate values? Yes, the array can contain positive integers, and duplicates are allowed.
What is the expected range of the array length and the values in it?
The length of nums
will be between 1 and 1000, and each integer in nums
will be between 1 and 1000.
How should the function behave if the array length is less than 3?
If the length of nums
is less than 3, it should return 0, as it’s not possible to form a triplet.
nums
is less than 3, return 0 immediately.i
, j
, and k
are distinct, increment a counter.This brute-force approach is feasible given the constraints (0 <= len(nums) <= 1000), making the maximum number of combinations ( \binom{1000}{3} \approx 166,167,000 ), which should be manageable.
#include <vector>
#include <unordered_set>
using namespace std;
int unequalTriplets(vector<int>& nums) {
int n = nums.size();
if (n < 3) return 0;
int count = 0;
// Iterate through all possible triplets
for (int i = 0; i < n - 2; ++i) {
for (int j = i + 1; j < n - 1; ++j) {
for (int k = j + 1; k < n; ++k) {
if (nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k]) {
++count;
}
}
}
}
return count;
}
n
length of nums
.The brute force approach should be acceptable given the constraints and allows us to directly count and verify the distinct property required for the triplets.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?