Here, we will see how to solve Number of Unequal Triplets in Array Solution of leet code 2475 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]
, andnums[k]
are pairwise distinct.- In other words,
nums[i] != nums[j]
,nums[i] != nums[k]
, andnums[j] != nums[k]
.
- In other words,
You have to return the number of triplets that meet the conditions.
Example 1:
Input: nums = [5,5,3,5,4] Output: 3 Explanation: The following triplets meet the conditions: - (0, 2, 4) because 5 != 3 != 4 - (1, 2, 4) because 5 != 3 != 4 - (2, 3, 4) because 3 != 5 != 4 Since there are 3 triplets, we return 3. Note that (2, 0, 4) is not a valid triplet because 2 > 0.
Example 2:
Input: nums = [2,2,2,2,2] Output: 0 Explanation: No triplets meet the conditions so we return 0.
Number of Unequal Triplets in Array Solution code in C++ and Go lang:
Here, we will be solving problem in multiple ways with code.
C++ code 1:
class Solution { public: int unequalTriplets(vector<int>& nums) { int n = nums.size(); int ret = n * (n - 1) * (n - 2) / 6; map<int, int> count; for (int i: nums) { count[i] += 1; } for (auto p: count) { int f = p.second; ret -= f * (f - 1) * (n - f) / 2; ret -= f * (f - 1) * (f - 2) / 6; } return ret; } };
C++ code 2:
class Solution { public: int unequalTriplets(vector<int>& nums) { int n = nums.size(); int ret = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (nums[i] == nums[j]) { continue; } for (int k = j + 1; k < n; ++k) { if (nums[k] == nums[j] || nums[k] == nums[i]) { continue; } ++ret; } } } return ret; } };
C++ code 3:
class Solution { public: int unequalTriplets(vector<int>& nums) { int count = 0; for(int i = 0; i < nums.size() - 2; i++) { for(int j = i + 1; j < nums.size() - 1; j++) { for(int k = j + 1; k < nums.size(); k++) { if ((nums[i] != nums[j]) && (nums[i] != nums[k]) && (nums[j] != nums[k])) { count++; } } } } return count; } };
Go code 1:
func unequalTriplets(nums []int) int { var i, j, k, count = 0, 0, 0, 0 for ; i < len(nums) - 2; i++ { for j = i + 1; j < len(nums) - 1; j++ { for k = j + 1; k < len(nums); k++ { if (nums[i] != nums[j]) && (nums[i] != nums[k]) && (nums[j] != nums[k]) { count++; } } } } return count }
Output:
Input: nums = [5,5,3,5,4] Output: 3
To check more leetcode problem’s solution. Pls click given below link:
https://techieindoor.com/category/leetcode/
https://techieindoor.com/category/leetcode/