Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highest frequency element in the dictionary

Tags:

swift

I am trying to find the highest frequency element in the given as follows.

First, I am trying to build a dictionary and count the each element based on frequency.

I am stuck how to extract max value from the constructed dictionary.

Input: [3,2,3]

Output: 3

func majorityElement(_ nums1: [Int]) -> Int {

    var num1Dict = Dictionary(nums1.map{ ($0, 1) }, uniquingKeysWith : +)
    return num1Dict.values.max() // ????

}
like image 665
casillas Avatar asked Dec 07 '25 10:12

casillas


1 Answers

You have correctly constructed num1Dict, which will be something like this for the input [3,2,3]:

[2:1, 3:2]

values.max() will return 2, because out of all the values in the dictionary (1 and 2), 2 is the highest.

See your error now?

You need to return the key associated with the highest value, not the highest value.

One very straightforward way is to do this:

func majorityElement(_ nums1: [Int]) -> Int? { // you should probably return an optional here in case nums1 is empty

    let num1Dict = Dictionary(nums1.map{ ($0, 1) }, uniquingKeysWith : +)
    var currentHigh = Int.min
    var mostOccurence: Int?
    for kvp in num1Dict {
        if kvp.value > currentHigh {
            mostOccurence = kvp.key
            currentHigh = kvp.value
        }
    }
    return mostOccurence

}
like image 174
Sweeper Avatar answered Dec 10 '25 01:12

Sweeper