Raman Mishra
Raman Mishra

Reputation: 2686

How can i make the following function more efficient?

Here is a function which makes a map from given array. Where key is the integer number and the value is the frequency of this number in the given array. I need to find the key which has the maximum frequency. If two key has the same frequency then i need to take the key which is smaller.

that's what i have written:

def findMinKeyWithMaxFrequency(arr: List[Int]): Int = {
    val ansMap:scala.collection.mutable.Map[Int,Int] = scala.collection.mutable.Map()

    arr.map(elem=> ansMap+=(elem->arr.count(p=>elem==p)))
    ansMap.filter(_._2==ansMap.values.max).keys.min
  }
val arr = List(1, 2 ,3, 4, 5, 4, 3, 2, 1, 3, 4)

val ans=findMinKeyWithMaxFrequency(arr) // output:3

How can i make it more efficient, it is giving me the right answer but i don't think it's the most efficient way to solve the problem.

In the given example the frequency of 3 and 4 is 3 so the answer should be 3 as 3 is smaller than 4.

Edit 1:

That's what i have done to make it bit efficient. Which is converting arr into Set as we need to find frequency for the unique elements only.

def findMinKeyWithMaxFrequency(arr: List[Int]): Int = {
    val ansMap=arr.toSet.map{ e: Int =>(e,arr.count(x=>x==e))}.toMap

    ansMap.filter(_._2==ansMap.values.max).keys.min
  }

Can it be more efficient? Is it the most functional way of writing the solution for the given problem.

Upvotes: 0

Views: 91

Answers (1)

jwvh
jwvh

Reputation: 51271

def findMinKeyWithMaxFrequency(arr: List[Int]): Int =
  arr.groupBy(identity).toSeq.maxBy(p => (p._2.length,-p._1))._1

Use groupBy() to get an effective count for each element then, after flattening to a sequence of tuples, code the required rules to determine the maximum.

Upvotes: 3

Related Questions