JavaScript Program to Count Unequal Element Pairs from the Given Array
Last Updated :
29 Aug, 2024
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)
);
Using Hash Map
In this approach, we use a hash map (or an object in JavaScript) to count the occurrences of each element in the array. By leveraging the counts of each element, we can determine the number of unequal pairs efficiently.
JavaScript
function countUnequalPairs(arr) {
const frequency = {};
let totalPairs = 0;
let unequalPairs = 0;
// Step 1: Build frequency object
for (const element of arr) {
frequency[element] = (frequency[element] || 0) + 1;
}
// Step 2: Calculate total pairs
for (const key in frequency) {
totalPairs += frequency[key];
}
// Step 3: Calculate unequal pairs
for (const key in frequency) {
const count = frequency[key];
unequalPairs += count * (totalPairs - count);
}
// Since each pair is counted twice, divide the result by 2
return unequalPairs / 2;
}
// Example usage:
const arr1 = [6, 5, 2, 3, 5, 2, 2, 1];
console.log(countUnequalPairs(arr1)); // Output: 24
const arr2 = [1, 2, 3, 1, 2];
console.log(countUnequalPairs(arr2)); // Output: 8
Using a Set to Count Unique Elements and Calculate Pairs
In this approach, we use a Set to count the occurrences of each unique element in the array. By leveraging the counts of each unique element, we can determine the number of unequal pairs efficiently without needing nested loops or sorting.
Example:
JavaScript
function countUnequalPairs(arr) {
const elementCount = new Map();
let totalPairs = 0;
let totalElements = arr.length;
arr.forEach(num => {
if (elementCount.has(num)) {
elementCount.set(num, elementCount.get(num) + 1);
} else {
elementCount.set(num, 1);
}
});
elementCount.forEach(count => {
totalPairs += count * (totalElements - count);
totalElements -= count;
});
return totalPairs;
}
let arr1 = [6, 5, 2, 3, 5, 2, 2, 1];
console.log(countUnequalPairs(arr1));
let arr2 = [1, 2, 3, 1, 2];
console.log(countUnequalPairs(arr2));
Using Single-Pass Approach (Optimized)
Use an efficient method to count unequal pairs in a single pass through the array, avoiding nested loops. This method Optimized for large arrays, avoiding nested loops for efficient performance.
Example:
JavaScript
function countUnequalPairs(arr) {
const count = new Map();
let totalPairs = 0;
let totalElements = 0;
for (const num of arr) {
if (count.has(num)) {
totalPairs += (totalElements - count.get(num));
count.set(num, count.get(num) + 1);
} else {
count.set(num, 1);
totalPairs += totalElements;
}
totalElements++;
}
return totalPairs;
}
let arr1 = [6, 5, 2, 3, 5, 2, 2, 1];
console.log(countUnequalPairs(arr1));
let arr2 = [1, 2, 3, 1, 2];
console.log(countUnequalPairs(arr2));
Combinatorial Approach with Basic Array Operations
- Calculate Total Pairs: Calculate the total number of possible pairs in the array using combinatorics.
- Count Equal Pairs: Iterate through the array to count pairs where both elements are equal.
- Compute Unequal Pairs: Subtract the count of equal pairs from the total pairs to get the number of unequal pairs.
Steps:
- Calculate Total Pairs: Use the formula n(n−1)/2​, where n is the length of the array, to find the total number of pairs.
- Count Equal Pairs: Use nested loops to count the number of pairs with equal elements.
- Subtract Equal Pairs: Subtract the count of equal pairs from the total pairs to get the number of unequal pairs.
Example:
JavaScript
function countUnequalPairs(arr) {
const n = arr.length;
let totalPairs = 0;
let equalPairs = 0;
// Calculate total number of pairs
totalPairs = (n * (n - 1)) / 2;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (arr[i] === arr[j]) {
equalPairs++;
}
}
}
const unequalPairs = totalPairs - equalPairs;
return unequalPairs;
}
const arr1 = [6, 5, 2, 3, 5, 2, 2, 1];
const arr2 = [1, 2, 3, 1, 2];
console.log(countUnequalPairs(arr1));
console.log(countUnequalPairs(arr2));
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Introduction to Tree Data Structure Tree data structure is a hierarchical structure that is used to represent and organize data in the form of parent child relationship. The following are some real world situations which are naturally a tree.Folder structure in an operating system.Tag structure in an HTML (root tag the as html tag) or
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
Use Case Diagram - Unified Modeling Language (UML) A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
9 min read