find the kth least common element in an array in swift

One way to find the kth least common element in an array is by using counting and sorting algorithms.

Here's a possible implementation in Swift:

main.swift
func kthLeastCommonElement(in array: [Int], k: Int) -> Int? {
    // Count the frequency of each element in the array
    var frequency = [Int: Int]()
    for element in array {
        frequency[element, default: 0] += 1
    }
    
    // Sort the elements by increasing frequency
    let sortedElements = array.sorted { frequency[$0]! < frequency[$1]! }
    
    // Find the kth least common element
    var count = 0
    var currentElement: Int?
    for element in sortedElements {
        if element != currentElement {
            count += 1
            currentElement = element
        }
        if count == k {
            return element
        }
    }
    
    // If there are less than k distinct elements in the array, return nil
    return nil
}
758 chars
27 lines

The function takes an array of integers and a positive integer k as input, and returns the kth least common element in the array, or nil if there are less than k distinct elements in the array.

The function first counts the frequency of each element in the array using a dictionary. Then, it sorts the elements in increasing order of frequency using the sorted method with a custom comparator that compares the frequency of two elements. Finally, it iterates over the sorted elements and keeps track of the distinct elements encountered so far and their counts. When it reaches the kth distinct element, it returns it.

gistlibby LogSnag