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,938 questions

51,875 answers

573 users

How to find the most common pair of characters in a string with TypeScript

1 Answer

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

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

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

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

    return maxPair;
}

const str: string = "xzvxdeshaalzxzmdedenlopxzxzxzaaqdewrzaaaapeerxz";

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



/*
run:

"Max count: 6" 
"The most common pair is: xz" 

*/

 



answered Nov 28, 2024 by avibootz

Related questions

...