find the kth most frequent element in an array in swift

Here's an implementation in Swift:

main.swift
func findKthMostFrequentElement(in array: [Int], k: Int) -> Int? {
    // Create a dictionary to keep track of the frequency of each element
    var frequencyDict = [Int: Int]()
    for num in array {
        frequencyDict[num, default: 0] += 1
    }
    
    // Sort the dictionary by frequency in descending order
    let sortedByFrequency = frequencyDict.sorted { $0.1 > $1.1 }
    
    // Check if k is within the bounds of the sorted array
    if k >= sortedByFrequency.count {
        return nil
    }
    
    // Return the kth most frequent element
    return sortedByFrequency[k].key
}
595 chars
19 lines

The function takes in an array of integers and an integer k, and returns the kth most frequent element in the array. It does this by first creating a dictionary to keep track of the frequency of each element in the array. Then, it sorts the dictionary by frequency in descending order, since we are looking for the most frequent elements. Finally, it checks if k is within the bounds of the sorted array (i.e. if k is larger than or equal to the length of the array). If it is, it returns nil. Otherwise, it returns the kth most frequent element, which is the key at the kth index of the sorted array.

gistlibby LogSnag