How to use a Map to Count Characters In Javascript

Using a Map, the approach counts characters by iterating over the string. For each character, it updates the count in the Map. Finally, it calculates the count of equal pairs by summing up the counts multiplied by one less than the count.

Example: This function counts the number of equal adjacent pairs in a string by using a Map to track the count of each character.

JavaScript
function countEqualPairs(str) {
    let count = 0;
    let charCount = new Map();
    for (let char of str) {
        if (charCount.has(char)) {
            count += charCount.get(char);
            charCount.set(char, charCount.get(char) + 1);
        } else {
            charCount.set(char, 1);
        }
    }
    return count;
}

console.log(countEqualPairs("abccba")); // 5

Output
3


JavaScript Program Count number of Equal Pairs in a String

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: 3
Explanation:
3 pairs that are equal are (p, p), (q, q) and (r, r)
Input: 'HelloWorld'
Output: 18

Table of Content

  • Naive Approach
  • Efficient appraoch
  • Using a Map to Count Characters

Similar Reads

Naive Approach

The straightforward method involves using two nested loops to iterate through the string, identifying all pairs, and maintaining a count of these pairs....

Efficient appraoch

In 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....

Using a Map to Count Characters

Using a Map, the approach counts characters by iterating over the string. For each character, it updates the count in the Map. Finally, it calculates the count of equal pairs by summing up the counts multiplied by one less than the count....

Contact Us