import scala.collection.mutable object TopKFrequentElements { def topKFrequent(nums: Array[Int], k: Int): List[Int] = { // Step 1: Create a frequency map val freqMap = nums.groupBy(identity).mapValues(_.length) // Step 2: Use a priority queue to keep track of top K frequent elements // The priority queue will be based on the frequency of elements val pq = mutable.PriorityQueue[(Int, Int)]()(Ordering.by(_._2)) // Step 3: Iterate over the frequency map for ((num, freq) <- freqMap) { pq.enqueue((num, freq)) if (pq.size > k) pq.dequeue() } // Step 4: Extract the top K frequent elements from the priority queue pq.map(_._1).toList } def main(args: Array[String]): Unit = { val nums = Array(1, 1, 1, 2, 2, 3) val k = 2 println(s"Top $k frequent elements: ${topKFrequent(nums, k)}") // Expected output: List(1, 2) } }