find the kth least frequent element in an array in swift

Here's one way to find the kth least frequent element in an array in Swift:

main.swift
func kthLeastFrequentElement(array: [Int], k: Int) -> Int? {
    // Create a dictionary to keep track of frequency of each element
    var frequencyDict = [Int: Int]()
    for element in array {
        frequencyDict[element, default: 0] += 1
    }

    // Sort the dictionary by frequency in ascending order
    let sortedByFrequency = frequencyDict.sorted { $0.value < $1.value }
    
    // Check if k is within the range of frequencies
    guard k > 0, k <= sortedByFrequency.count else {
        return nil
    }

    // Return the kth least frequent element
    return sortedByFrequency[k-1].key
}
604 chars
19 lines

Here's an example of how to use this function:

main.swift
let array = [2, 1, 1, 3, 2, 3, 3]
let k = 2

if let kthLeastFrequent = kthLeastFrequentElement(array: array, k: k) {
    print("The \(k)th least frequent element is \(kthLeastFrequent)")
} else {
    print("Invalid value of k")
}
230 chars
9 lines

Output:

main.swift
The 2th least frequent element is 2
36 chars
2 lines

gistlibby LogSnag