How to find the element with minimum occurrences in a list with Scala

1 Answer

0 votes
object FrequencyUtils:

  /** Finds the element with the minimum number of occurrences in a sequence.
    *
    * @tparam A
    *   The element type within the sequence.
    * @param seq
    *   The input sequence to process.
    * @return
    *   An [[Option]] containing the least frequent element, or [[None]] if the
    *   sequence is empty.
    */
  def minOccurrence[A](seq: Seq[A]): Option[A] =
    if seq.isEmpty then None
    else
      // 1. groupMapReduce tallies frequencies in a single pass O(N) 
      //    without intermediate collection overhead
      val counts: Map[A, Int] = seq.groupMapReduce(identity)(_ => 1)(_ + _)

      // 2. minByOption safely finds the (element, count) 
      //    tuple with the lowest count in O(K) time
      counts.minByOption(_._2).map(_._1)

@main def runMinOccurrenceExample(): Unit =
  val lst: List[Int] = List(1, 3, 1, 1, 4, 4, 5, 5, 4, 2, 2, 2, 3, 3, 3)

  FrequencyUtils.minOccurrence(lst) match
    case Some(result) => println(result) // Output: 5
    case None         => println("The collection was empty.")



/*
run:

5

*/

 



answered Sep 26 by avibootz
...