find the kth most common element in an array in swift

To find the kth most common element in an array, one approach is to use a dictionary to count the occurrence of each element in the array, and then sort the dictionary by value in descending order.

Here's an implementation in Swift:

main.swift
func kthMostCommonElement<T: Hashable>(_ array: [T], k: Int) -> T? {
    var counts: [T: Int] = [:]
    for element in array {
        counts[element, default: 0] += 1
    }
    let sortedCounts = counts.sorted { $0.value > $1.value }
    if k <= sortedCounts.count {
        return sortedCounts[k - 1].key
    }
    return nil
}
330 chars
12 lines

This function takes an array of elements of type T, and an integer k, and returns the kth most common element in the array, or nil if there is no such element (i.e., if k is greater than the number of distinct elements in the array).

The function first defines a dictionary counts to count the occurrence of each element in the array. The loop iterates over the array, and for each element, increments its count in the dictionary.

The function then sorts the dictionary by value in descending order using the sorted method, and checks if the kth element exists in the sorted dictionary. If so, it returns the key of that element (i.e., the actual element value). If not, it returns nil.

gistlibby LogSnag