Count frequency of each element in an array

[Question]: Count frequency of each element in a given array .
For example: Given Array [5,4,5,5,6,9,5,6]. Output is [4: 1, 6: 2, 9: 1, 5: 4] Which indicates 4 is 1 time, 6 is 2 times and so on…
#Approach 1: – Use HashMap /Dictionary . Because dictionary key are unique so we can use of that & keep values as counter

// TC: O(n)
// SC: O(n)
func findOccurance(_ arr: [Int]) -> [Int:Int] {
    
    var hashObject: [Int:Int] = [:]
    for obj in arr {
        if hashObject[obj] == nil {
            hashObject[obj] = 1
        } else {
            hashObject[obj]! += 1
        }
    }
    return hashObject
}

var anArray = [5,4,5,5,6,9,5,6]
let hashObj = findOccurance(anArray)
print("Hash obj---", hashObj) // [4: 1, 6: 2, 9: 1, 5: 4]

Leave a Comment

Your email address will not be published. Required fields are marked *