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

...