How to find the element with minimum occurrences in an array with Swift

1 Answer

0 votes
import Foundation

/// Finds the element with the minimum number of occurrences in a sequence.
///
/// - Parameter sequence: The input sequence to evaluate.
/// - Returns: The least frequent element, or `nil` if the sequence is empty.
func minOccurrence<S: Sequence>(in sequence: S) -> S.Element? where S.Element: Hashable {
    // 1. Tally element frequencies into a Dictionary [T: Int] in O(N) time
    let counts = sequence.reduce(into: [S.Element: Int]()) { counts, item in
        counts[item, default: 0] += 1
    }
    
    // 2. Find the key-value pair with the minimum count in O(K) time
    return counts.min(by: { $0.value < $1.value })?.key
}

// Example usage:
let lst = [1, 3, 1, 1, 4, 4, 5, 5, 4, 2, 2, 2, 3, 3, 3]

if let result = minOccurrence(in: lst) {
    print(result) // Output: 5
} else {
    print("The array was empty.")
}


/*
run:

5

*/

 



answered Sep 26 by avibootz
...