How to Find the difference between highest & lowest occurring elements in an array ?

[Question]: In given array find difference between lowest & highest occurrence elements .
For Example: Array :  [5,4,5,5,6,9,5,6] O/P = 2. because 5 appears 4 times & element 6 is 2 times. difference is 2.

// Question diffrence between highest & lowest occurance of a number in an array..
// TC: O(n)
// SC: O(n)
func findDiffranceBetweenHighLowOccurance(_ arr: [Int]) -> Int {
    
    var hashObject: [Int:Int] = [:]
    for obj in arr {
        if hashObject[obj] == nil {
            hashObject[obj] = 1
        } else {
            hashObject[obj]! += 1
        }
    }
    
    let sortedObj = hashObject.sorted { $0.value > $1.value }
    if sortedObj.count > 1 {
       return sortedObj[0].value - sortedObj[1].value
    }
    return -1
}

var anArray = [5,4,5,5,6,9,5,6]
let diffrence = findDiffranceBetweenHighLowOccurance(anArray)
print("diffrence", diffrence) // 2

Leave a Comment

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