Sort Characters By Frequency

[Questions]: Given a string s, sort it in decreasing order based on the frequency of the characters. for example “tree” so ee has highest appearance hence answer will be eert

Return the sorted string. If there are multiple answers, return any of them
Input: s = “tree”
Output: “eert”

// TC: O(N)
// SC: O(N)
func frequencySort(_ s: String) -> String {
    var dict:[Character:String] = [:]
    for c in s {
        dict[c, default:""] += String(c)
    }
    //        var sortedDictionary = dict.sorted { (aDic, bDic) -> Bool in
    //            return aDic.value.count > bDic.value.count
    //        }
    // Here we can also use some sorting technique, like merge sort
    var sortedDictionary = dict.sorted {
        $0.1.count > $1.1.count
    }
    var ans = ""
    for (_, value) in sortedDictionary {
        ans += value
    }
    return ans
}
//Other Solution using high order functions.
/*
func frequencySort(_ s: String) -> String {
    let counts = s.reduce(into: [:]) {$0[$1, default: 0] += 1}
    let sortedCounts = counts.sorted(by: { $0.value > $1.value })
    return sortedCounts.reduce(into: "") {$0.append(
        String(repeating: $1.0, count: $1.1))
    }
}
func frequencySort(_ s: String) -> String {
    return Dictionary(s.map { ($0, 1)}, uniquingKeysWith: +)
        .sorted(by: { $0.value > $1.value })
        .reduce("") { $0 + String(repeating: $1.key, count: $1.value) }
}
 func frequencySort(_ s: String) -> String {
     var dic = [Character: String]()
     var ans = ""
     
     s.map{ dic[$0, default: ""] += String($0) }
     dic.sorted{ $0.1.count > $1.1.count }.map{ ans += $0.1 }
     
     return ans
 }
*/
 
let strObj = "tree"
let opSortedStr = frequencySort(strObj)
print(" opSortedStr-- ", opSortedStr)// eert

Leave a Comment

Your email address will not be published. Required fields are marked *