Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2475. Number of Unequal Triplets in Array

Explanation

To solve this problem, we can iterate through all possible triplets (i, j, k) and check if they meet the conditions. We need to make sure that the elements at indices i, j, and k are pairwise distinct. We can achieve this by using three nested loops. If the conditions are met, we increment a counter to keep track of the number of valid triplets. Finally, we return the count of valid triplets.

  • Time Complexity: O(n^3) where n is the length of the input array nums.
  • Space Complexity: O(1) as we are using constant extra space.
class Solution {
    public int countGoodTriplets(int[] nums) {
        int n = nums.length;
        int count = 0;
        
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; 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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.