JavaScript Program Count number of Equal Pairs in a String Last Updated : 18 Jul, 2024 Comments Improve Suggest changes Like Article Like Report In this article, we are going to learn how can we count a number of equal pairs in a string. Counting equal pairs in a string involves finding and counting pairs of consecutive characters that are the same. This task can be useful in various applications, including pattern recognition and data analysis. Examples:Input: 'pqr'Output: 3Explanation:3 pairs that are equal are (p, p), (q, q) and (r, r)Input: 'HelloWorld'Output: 18Table of ContentNaive ApproachEfficient AppraochUsing Combinatorial CountingNaive ApproachThe straightforward method involves using two nested loops to iterate through the string, identifying all pairs, and maintaining a count of these pairs.Example: JavaScript // JavaScript program to determine // the count of equal character pairs // Function to calculate the // count of equal character pairs function fun(str) { // Length of the input string let strLength = str.length; // Variable to store the // count of equal character pairs let pairCount = 0; // Nested loops to compare // characters for equal pairs for (let i = 0; i < strLength; i++) { for (let j = 0; j < strLength; j++) { // If an equal pair is found if (str[i] == str[j]) { pairCount++; } } } return pairCount; } // Driver Code let str = "geeksforgeeks"; console.log(fun(str)); Output31 Time Complexity: O(n2), n is the length of input stringSpace Complexity: O(1)Efficient AppraochIn this approach, We must efficiently determine the count of distinct pairs of characters in linear time. Notably, pairs like (x, y) and (y, x) are treated as distinct. To accomplish this, we employ a hash table to record the occurrences of each character. If a character appears twice, it corresponds to 4 pairs: (i, i), (j, j), (i, j), and (j, i). By utilizing a hashing mechanism, we keep track of the frequency of each character, and for each character, the count of pairs will be the square of its frequency. The hash table will have a length of 256 since there are 256 distinct characters.Example: This example shows the use of the above-explined approach. JavaScript // JavaScript program to calculate the // count of pairs const MAX = 256 // Function to calculate the count // of identical pairs function fun(str) { // Hash table to store // character counts let charCount = new Array(MAX).fill(0) // Iterate through the string and tally // the occurrences of each character for (let i = 0; i < str.length; i++) charCount[str.charCodeAt(i) - 97] += 1 // Variable to hold the final count of pairs let pairCount = 0 // Iterate through the characters and check // for occurrences for (let i = 0; i < MAX; i++) pairCount += charCount[i] * charCount[i] return pairCount } // Driver code let str = "abccba" console.log(fun(str)) Output3 Time Complexity: O(n), n is the length of input stringSpace Complexity: O(1)Using Combinatorial CountingAnother efficient approach to count the number of equal pairs in a string is by using combinatorial counting principles. This approach leverages the fact that the number of ways to choose 2 items from n items (where order does not matter) is given by the combination formula C(n, 2) = n * (n - 1) / 2.Example: JavaScript function countEqualPairs(s) { let freq = {}; for (let char of s) { if (freq[char]) { freq[char]++; } else { freq[char] = 1; } } let totalPairs = 0; for (let count of Object.values(freq)) { if (count > 1) { totalPairs += (count * (count - 1)) / 2; } } return totalPairs; } const inputStr = 'HelloWorld'; const output = countEqualPairs(inputStr); console.log(output); Output4 Comment More infoAdvertise with us Next Article JavaScript Program Count number of Equal Pairs in a String A anjugaeu01 Follow Improve Article Tags : JavaScript Web Technologies Geeks Premier League javascript-string JavaScript-DSA JavaScript-Program Geeks Premier League 2023 +3 More Similar Reads JavaScript Program to Count Unequal Element Pairs from the Given Array 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, 4 min read JavaScript Program to Count the Occurrences of Each Character Here are the various methods to count the occurrences of each characterUsing JavaScript ObjectThis is the most simple and widely used approach. A plain JavaScript object (obj) stores characters as keys and their occurrences as values.JavaScriptconst count = (s) => { const obj = {}; for (const cha 3 min read JavaScript Program to Count the Occurrences of a Specific Character in a String In this article, we will see how to count the frequency of a specific character in a string with JavaScript. Counting the frequency of a specific character in a string is a common task in JavaScript. Example: Input : S = âgeeksforgeeksâ and c = âeâOutput : 4Explanation: âeâ appears four times in str 3 min read JavaScript Count Distinct Occurrences as a Subsequence Counting the distinct occurrences is the most common problem in string manipulation. Subsequences are the subsets of the characters in the string which appear in the same order but not necessarily in a consecutive manner. In the problem, the task is to find out the count of how many times a given su 6 min read Java Program to Count Number of Digits in a String The string is a sequence of characters. In java, objects of String are immutable. Immutable means that once an object is created, it's content can't change. Complete traversal in the string is required to find the total number of digits in a string. Examples: Input : string = "GeeksforGeeks password 2 min read Java Program to Count the Total Number of Vowels and Consonants in a String Given a String count the total number of vowels and consonants in this given string. Assuming String may contain only special characters, or white spaces, or a combination of all. The idea is to iterate the string and checks if that character is present in the reference string or not. If a character 2 min read JavaScript - How To Count String Occurrence in String? Here are the various methods to count string occurrence in a string using JavaScript.1. Using match() Method (Common Approach)The match() method is a simple and effective way to count occurrences using a regular expression. It returns an array of all matches, and the length of the array gives the co 3 min read Java Program to Print all Unique Words of a String Java program to print all unique words present in the string. The task is to print all words occurring only once in the string. Illustration: Input : Welcome to Geeks for Geeks. Output : Welcome to for Input : Java is great.Python is also great. Output : Java Python also Methods: This can be done in 4 min read Count a Group of Words in a String Using Regex in Java Regular Expression is a powerful approach in Java for searching, Manipulating, and matching patterns with specific pattern requirements. In this article, we will learn to count a group of words in a string using regex. First I explain count a group of words in a string using regex as per requirement 4 min read Check if number of distinct characters in 2 Strings can be made equal Given two strings A and B of lowercase English letters of lengths N and M respectively. Check whether the number of distinct characters in both strings A and B can be made equal by applying the operation at most one time. Where operation is: Choose any index i such that 0 ⤠i ⤠N from string A and i 15 min read Like