Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,936 questions

51,873 answers

573 users

How to find the most common pair of characters in a string with Node.js

1 Answer

0 votes
function getMostCommonPair(str) {
    // Object to store pairs and their counts
    const pairCounts = {};
    const size = str.length;

    // Iterate through the string
    for (let i = 0; i < size - 1; i++) {
        // Get the current pair of characters
        const pair = str[i] + str[i + 1];

         if (pairCounts[pair]) {
            pairCounts[pair]++;
        } else {
            pairCounts[pair] = 1;
        }
    }

    // Find the pair with the highest count
    let maxPair = '';
    let maxCount = 0;
    for (const pair in pairCounts) {
        if (pairCounts[pair] > maxCount) {
            maxCount = pairCounts[pair];
            maxPair = pair;
        }
    }
    
    console.log("Max count: " + maxCount);

    return maxPair;
}

const str = "xzvxdesxzhdeaalzxzmdenlopxzxzxzaaqdewrzaaaapeerxzxz";

console.log("The most common pair is: " + getMostCommonPair(str)); 



/*
run:

Max count: 8
The most common pair is: xz

*/

 



answered Nov 28, 2024 by avibootz
...