Open In App

JavaScript Program to Count Unequal Element Pairs from the Given Array

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Unequal element pairs in an array refer to pairs of distinct elements within the array that have different values. These pairs consist of two elements that are not equal to each other, highlighting their inequality when compared in the context of the array’s values.

Examples:

Input: arr[] = {6, 5, 2, 3, 5, 2, 2, 1} 
Output: 2 
Explanation: (arr[1], arr[4]) and (arr[2], arr[5]) are the only possible pairs.
Input: arr[] = {1, 2, 3, 1, 2} 
Output: 2 

Using Sort() method

In this approach, the function countUnequalPairs sorts the input array, and then iterates through unique elements. For each element, it compares with the rest of the array, counting unequal pairs. The result represents the count of unequal pairs.

Syntax

array.sort()

Example: This example shows the use of the above-explained approach.

Javascript




const countUnequalPairs = (
    inputArray) => {
    inputArray.sort((a, b) => a - b);
    let unEqualPairsCount = 0;
    for (
        let i = 0;
        i < inputArray.length;) {
        let currentElement =
            inputArray[i];
        let j = i + 1;
        for (let num of inputArray.slice(j)) {
            if (
                num !== currentElement) {
                unEqualPairsCount++;
            }
        }
        i = j;}
    return unEqualPairsCount;
};
  
const testArray = [1, 1, 2];
console.log(
    countUnequalPairs(testArray)
);


Output

2

Using nested loops

In this approach, the unequalPairs function counts unique unequal pairs within an array by comparing each element with subsequent elements. It uses nested loops, iterating through the array and checking for inequality.

Syntax:

for (let i = 0; i < arr.length; i++) {
        for (let num of arr.slice(i + 1)) {
            if (arr[i] !== num) {
                count++;
            }
        }
    }

Example: This example shows the use of the above-explained approach.

Javascript




const unequalPairs = (inputArray) => {
    let unequalPairsCounts = 0;
    for (
        let i = 0;
        i < inputArray.length;
        i++) {
        for (let num of inputArray.slice(i + 1)) {
            if (inputArray[i] !== num) {
                unequalPairsCounts++;
            }}}
    return unequalPairsCounts;
};
  
const testArray1 = [1, 1, 2];
const testArray2 = [1, 2, 3];
console.log(unequalPairs(testArray1));
console.log(unequalPairs(testArray2));


Output

2
3


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads