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

1 Answer

0 votes
func findMostCommonPair(in s: String) -> (pair: String, count: Int)? {
    var pairFrequency: [String: Int] = [:]
    
    // Iterate through the string to get pairs of characters
    for i in 0..<(s.count - 1) {
        let startIndex = s.index(s.startIndex, offsetBy: i)
        let endIndex = s.index(startIndex, offsetBy: 1)
        let pair = String(s[startIndex...endIndex])
        
        // Update the frequency dictionary
        pairFrequency[pair, default: 0] += 1
    }
    
    // Find the most common pair
    if let (mostCommonPair, count) = pairFrequency.max(by: { $0.value < $1.value }) {
        return (mostCommonPair, count)
    }
    
    return nil
}

let s = "xzvxdeshaalzxzmdenlopxzxzxzaaqdewrzaaaapeerxzxz";

if let result = findMostCommonPair(in: s) {
    print("Most common pair: \(result.pair) with count: \(result.count)")
} else {
    print("No pairs found.")
}




/*
run:

Most common pair: xz with count: 7

*/

 



answered Nov 28, 2024 by avibootz

Related questions

...