Open In App

Count unequal element pairs from the given Array

Last Updated : 19 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of N elements. The task is to count the total number of indices (i, j) such that arr[i] != arr[j] and i < j.
Examples: 

Input: arr[] = {1, 1, 2} 
Output:
(1, 2) and (1, 2) are the only valid pairs.
Input: arr[] = {1, 2, 3} 
Output: 3
Input: arr[] = {1, 1, 1} 
Output:

Approach: Initialise a count variable cnt = 0 and run two nested loops to check every possible pair whether the current pair is valid or not. If it is valid, then increment the count variable. Finally, print the count of valid pairs.

Algorithm:

  • Define a static method named “countPairs” that takes two parameters, an integer array “arr” and an integer “n”, and returns an integer.
  • Declare an integer variable “cnt” and initialize it to 0. This variable will store the count of valid pairs.
  • Use a nested for-loop to iterate through each index pair (i, j) of the input array “arr”.
  • If the current pair of values at indices i and j are different, then increment the “cnt” variable by 1. This indicates that the current pair is a valid pair.
  • Return the final value of “cnt”.

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the
// count of valid pairs
int countPairs(int arr[], int n)
{
  
    // To store the required count
    int cnt = 0;
  
    // For each index pair (i, j)
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
  
            // If current pair is valid
            // then increment the count
            if (arr[i] != arr[j])
                cnt++;
        }
    }
    return cnt;
}
  
// Driven code
int main()
{
    int arr[] = { 1, 1, 2 };
    int n = sizeof(arr) / sizeof(int);
  
    cout << countPairs(arr, n);
  
    return 0;
}


Java




// Java implementation of the approach 
class GFG 
{
      
    // Function to return the 
    // count of valid pairs 
    static int countPairs(int arr[], int n) 
    
      
        // To store the required count 
        int cnt = 0
      
        // For each index pair (i, j) 
        for (int i = 0; i < n; i++) 
        
            for (int j = i + 1; j < n; j++) 
            
      
                // If current pair is valid 
                // then increment the count 
                if (arr[i] != arr[j]) 
                    cnt++; 
            
        
        return cnt; 
    
      
    // Driven code 
    public static void main (String[] args)
    
        int arr[] = { 1, 1, 2 }; 
        int n = arr.length; 
      
        System.out.println(countPairs(arr, n)); 
    
}
  
// This code is contributed by AnkitRai01


Python3




# Python3 implementation of the approach 
  
# Function to return the
# count of valid pairs
def countPairs(arr, n):
  
    # To store the required count
    cnt = 0;
  
    # For each index pair (i, j)
    for i in range(n):
        for j in range(i + 1, n):
  
            # If current pair is valid
            # then increment the count
            if (arr[i] != arr[j]):
                cnt += 1;
  
    return cnt;
  
# Driver code
if __name__ == '__main__':
    arr = [ 1, 1, 2 ];
    n = len(arr);
  
    print(countPairs(arr, n));
      
# This code is contributed by 29AjayKumar


C#




// C# implementation of the approach 
using System;
  
class GFG 
{
      
    // Function to return the 
    // count of valid pairs 
    static int countPairs(int []arr, int n) 
    
      
        // To store the required count 
        int cnt = 0; 
      
        // For each index pair (i, j) 
        for (int i = 0; i < n; i++) 
        
            for (int j = i + 1; j < n; j++) 
            
      
                // If current pair is valid 
                // then increment the count 
                if (arr[i] != arr[j]) 
                    cnt++; 
            
        
        return cnt; 
    
      
    // Driven code 
    public static void Main()
    
        int []arr = { 1, 1, 2 }; 
        int n = arr.Length; 
      
        Console.WriteLine(countPairs(arr, n)); 
    
}
  
// This code is contributed by AnkitRai01


Javascript




<script>
  
// Javascript implementation of the approach
  
// Function to return the
// count of valid pairs
function countPairs(arr, n)
{
  
    // To store the required count
    var cnt = 0;
  
    // For each index pair (i, j)
    for (var i = 0; i < n; i++) {
        for (var j = i + 1; j < n; j++) {
  
            // If current pair is valid
            // then increment the count
            if (arr[i] != arr[j])
                cnt++;
        }
    }
    return cnt;
}
  
// Driven code
var arr = [ 1, 1, 2 ];
var n = arr.length;
document.write(countPairs(arr, n));
  
</script>


Output

2

Time Complexity: O(N2)
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Approach 2: Count unequal element pairs from the given Array Using Recursion.

Algorithm:

1. Create function “countPairsRec” which takes array “arr[ ]” and indices “i”  and “j” .

2. If the value of “i” is larger than or equal to the value of “j”, the function returns 0 because there are no more pairs to compare.

3. Otherwise, determine whether the pair (arr[i], arr[j]) is a valid pair. If it is valid, increase the count by one and call the function again with the next pair.

4. If the pair (arr[i], arr[j]) is invalid, go to the next pair without increasing the count.

5. At the end of the function, return the count.

6. Create a new function called “countPairs” that accepts an integer array “arr” and an integer “n” as input parameters.

7. In the function, call the “countPairsRec” function with the array’s starting and ending indices.

Here’s the implementation:

C++




#include <bits/stdc++.h>
using namespace std;
  
// Function to recursively count the number of valid pairs
int countPairsRec(int arr[], int i, int j) {
    // Base case: if we've compared all pairs, return 0
    if (i >= j) {
        return 0;
    }
      
    // Recursive case:
    // If the current pair is valid, add 1 and move on to the next pair
    if (arr[i] != arr[j]) {
        return 1 + countPairsRec(arr, i+1, j) + countPairsRec(arr, i, j-1);
    }
    // If the current pair is invalid, move on to the next pair without counting it
    else {
        return countPairsRec(arr, i+1, j) + countPairsRec(arr, i, j-1);
    }
}
  
// Wrapper function to call the recursive function
int countPairs(int arr[], int n) {
    return countPairsRec(arr, 0, n-1);
}
  
// Driver code
int main() {
    int arr[] = {1, 2, 3};
    int n = sizeof(arr) / sizeof(int);
    cout << countPairs(arr, n) << endl;
    return 0;
}
  
// This code is contributed by Vaibhav Saroj


C




#include <stdio.h>
  
// Function to recursively count the number of valid pairs
int countPairsRec(int arr[], int i, int j) {
    // Base case: if we've compared all pairs, return 0
    if (i >= j) {
        return 0;
    }
      
    // Recursive case:
    // If the current pair is valid, add 1 and move on to the next pair
    if (arr[i] != arr[j]) {
        return 1 + countPairsRec(arr, i+1, j) + countPairsRec(arr, i, j-1);
    }
    // If the current pair is invalid, move on to the next pair without counting it
    else {
        return countPairsRec(arr, i+1, j) + countPairsRec(arr, i, j-1);
    }
}
  
// Wrapper function to call the recursive function
int countPairs(int arr[], int n) {
    return countPairsRec(arr, 0, n-1);
}
  
// Driver code
int main() {
    int arr[] = {1, 2, 3};
    int n = sizeof(arr) / sizeof(int);
    printf("%d\n", countPairs(arr, n));
    return 0;
}
  
// This code is contributed by Vaibhav Saroj


Java




/*package whatever //do not write package name here */
import java.util.*;
  
class Main {
      
    // Function to recursively count the number of valid pairs
    static int countPairsRec(int arr[], int i, int j) {
        // Base case: if we've compared all pairs, return 0
        if (i >= j) {
            return 0;
        }
  
        // Recursive case:
        // If the current pair is valid, add 1 and move on to the next pair
        if (arr[i] != arr[j]) {
            return 1 + countPairsRec(arr, i+1, j) + countPairsRec(arr, i, j-1);
        }
        // If the current pair is invalid, move on to the next pair without counting it
        else {
            return countPairsRec(arr, i+1, j) + countPairsRec(arr, i, j-1);
        }
    }
  
    // Wrapper function to call the recursive function
    static int countPairs(int arr[], int n) {
        return countPairsRec(arr, 0, n-1);
    }
  
    // Driver code
    public static void main(String[] args) {
        int arr[] = {1, 2, 3};
        int n = arr.length;
        System.out.println(countPairs(arr, n));
    }
}
  
  
// This code is contributed by Vaibhav Saroj


Python3




def countPairsRec(arr, i, j):
    # Base case: if we've compared all pairs, return 0
    if i >= j:
        return 0
  
    # Recursive case:
    # If the current pair is valid, add 1 and move on to the next pair
    if arr[i] != arr[j]:
        return 1 + countPairsRec(arr, i + 1, j) + countPairsRec(arr, i, j - 1)
    # If the current pair is invalid, move on to the next pair without counting it
    else:
        return countPairsRec(arr, i + 1, j) + countPairsRec(arr, i, j - 1)
  
  
# Wrapper function to call the recursive function
def countPairs(arr):
    return countPairsRec(arr, 0, len(arr) - 1)
  
  
# Driver code
arr = [1, 2, 3]
print(countPairs(arr))


C#




using System;
  
class Program
{
    // Function to recursively count the number of valid pairs
    static int countPairsRec(int[] arr, int i, int j) {
        // Base case: if we've compared all pairs, return 0
        if (i >= j) {
            return 0;
        }
          
        // Recursive case:
        // If the current pair is valid, add 1 and move on to the next pair
        if (arr[i] != arr[j]) {
            return 1 + countPairsRec(arr, i+1, j) + countPairsRec(arr, i, j-1);
        }
        // If the current pair is invalid, move on to the next pair without counting it
        else {
            return countPairsRec(arr, i+1, j) + countPairsRec(arr, i, j-1);
        }
    }
  
    // Wrapper function to call the recursive function
    static int countPairs(int[] arr, int n) {
        return countPairsRec(arr, 0, n-1);
    }
  
    // Driver code
    static void Main(string[] args) {
        int[] arr = {1, 2, 3};
        int n = arr.Length;
        Console.WriteLine(countPairs(arr, n));
    }
}
  
// This code is contributed by Vaibhav Saroj


Javascript




function countPairsRec(arr, i, j) {
    // Base case: if we've compared all pairs, return 0
    if (i >= j) {
        return 0;
    }
      
    // Recursive case:
    // If the current pair is valid, add 1 and move on to the next pair
    if (arr[i] !== arr[j]) {
        return 1 + countPairsRec(arr, i+1, j) + countPairsRec(arr, i, j-1);
    }
    // If the current pair is invalid, move on to the next pair without counting it
    else {
        return countPairsRec(arr, i+1, j) + countPairsRec(arr, i, j-1);
    }
}
  
// Wrapper function to call the recursive function
function countPairs(arr) {
    return countPairsRec(arr, 0, arr.length-1);
}
  
// Driver code
const arr = [1, 2, 3];
console.log(countPairs(arr));
  
  
// This code is contributed by Vaibhav Saroj


Output

3

The Recursive approach is contributed by Vaibhav Saroj .

Time Complexity: O(n^2)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads