Leetcode 2475. Number of Unequal Triplets in Array
You are given a 0-indexed integer array nums
, and you are asked to return the total number of triplets (i, j, k)
such that:
0 <= i < j < k < nums.length
nums[i] != nums[j]
nums[j] != nums[k]
nums[i] != nums[k]
nums
?
nums
can be up to 1000.nums
?
nums
can be from 1
to 1000
.nums
.(i, j, k)
and check the conditions whether they are unequal. This approach would have a time complexity of (O(n^3)), where (n) is the length of the array.n
, we need a more optimized approach:
i
, j
, and k
, and check the inequality conditions.public class UnequalTriplets {
public static int unequalTriplets(int[] nums) {
int n = nums.length;
int count = 0;
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;
}
public static void main(String[] args) {
int[] nums1 = {1, 2, 3, 1};
System.out.println(unequalTriplets(nums1)); // Output: 1
int[] nums2 = {4, 4, 2, 4, 3};
System.out.println(unequalTriplets(nums2)); // Output: 3
int[] nums3 = {1, 1, 1, 1};
System.out.println(unequalTriplets(nums3)); // Output: 0
}
}
nums
. Each loop decreases the range of traversal for the succeeding loop.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?