Start learning free

LESSON 229 OF 291 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Most Frequent Element in Scala: Count, Then Scan in Order

Practice Read the full explanation

Given an array of integers nums, return the value that appears in it the most times.

If several values tie for the most appearances, return the one that shows up first in nums. nums has at least one number.

Example 1:

Input: nums = [1, 3, 2, 3, 1, 3]
Output: 3
Explanation: 3 appears three times, 1 twice and 2 once.

Example 2:

Input: nums = [5, 2, 2, 5, 9]
Output: 5
Explanation: 5 and 2 both appear twice. 5 shows up first (at index 0, while 2 first shows up at index 1), so the answer is 5.

Example 3:

Input: nums = [7]
Output: 7
Explanation: The only value is also the most frequent one.
STEP 1 OF 8
    Ctrl + Enter to check

    SCALA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Most Frequent Element in Scala, explained

    Problem overview

    The method mostFrequent receives an Array[Int] named nums with at least one number and returns the value that appears most often. When several values tie for the most appearances, the one that appears first in nums wins.

    For Array(1, 3, 2, 3, 1, 3) the answer is 3, which appears three times. For Array(5, 2, 2, 5, 9) both 5 and 2 appear twice, and 5 comes first in the array, so the answer is 5.

    Approach

    Do it in two passes. The first pass counts every value in a mutable map. The second pass walks nums again, in its original order, and keeps the value with the highest count. The order of the second pass is what settles ties: walking nums meets values in the order they first appear, and a later value replaces the current best only if its count is strictly greater.

    Walking the keys of the map instead would be a mistake, because a map doesn't promise any particular order, so a tie could be resolved differently from the lesson's rule.

    Other ways to solve it exist. The brute force counts each element by scanning the whole array again, which takes O(n²) time. Sorting first puts equal values side by side and counts runs in O(n log n), but sorting destroys the original order, so the "first in nums" rule would need extra bookkeeping. The map gets everything in two plain passes.

    Step by step

    1. Create the counts. scala.collection.mutable.Map[Int, Int]() in a val named counts: each value of nums is a key and its count is the value.
    2. First loop over nums with for (num <- nums).
    3. Seen before: if counts.contains(num), do counts(num) += 1.
    4. First time: otherwise, counts(num) = 1.
    5. Pick a starting best. var best = nums(0) is the answer until something beats it.
    6. Second loop over nums again, in order.
    7. Compare counts. If counts(num) > counts(best), then best = num. Strictly greater keeps the earlier value on a tie.
    8. Return best.

    The solution in Scala

    class Solution {
        def mostFrequent(nums: Array[Int]): Int = {
            val counts = scala.collection.mutable.Map[Int, Int]()
            for (num <- nums) {
                if (counts.contains(num)) {
                    counts(num) += 1
                } else {
                    counts(num) = 1
                }
            }
            var best = nums(0)
            for (num <- nums) {
                if (counts(num) > counts(best)) {
                    best = num
                }
            }
            return best
        }
    }
    
    • Int keys. A map's key can be any type. Here the keys are Int values, and counts(num) reads the count of the number num, not a position in a list.
    • Safe reads. counts(num) in the second loop never fails, because every number in nums was counted by the first loop. Reading a key that was never added would throw a NoSuchElementException.
    • Arrays are read with parentheses. nums(0) is the first element, because Scala treats an array lookup like a function call. Indexing starts at 0, and an index outside the array throws an ArrayIndexOutOfBoundsException, so nums(0) relies on the lesson's promise of at least one number.
    • val and var. counts is a val: the map is changed, never replaced. best is a var because it is reassigned.
    • Shorter counting. The first loop can be one line: counts(num) = counts.getOrElse(num, 0) + 1. For Array(5, 2, 2, 5, 9) it builds HashMap(2 -> 2, 5 -> 2, 9 -> 1). The map shows 2 before 5 in its printout, which is exactly why the second loop walks the array rather than the map.

    The cost is linear: each loop visits the numbers once, and a map lookup or update takes constant time on average, so the whole method is O(n) time. The map holds one entry per different value, which is extra space of at most n entries.

    Following the second pass

    For Array(5, 2, 2, 5, 9) the first pass builds HashMap(2 -> 2, 5 -> 2, 9 -> 1). The second pass starts with best = 5 and compares each number's count with the count of best:

    numcounts(num)best afterwards
    525
    225
    225
    525
    915

    The 2 ties with 5 at a count of 2, but a tie is not "greater", so 5 stays. Notice that the map lists 2 before 5. A loop over the map's entries could therefore have picked 2, which is the reason to walk nums in the second pass.

    The second loop keeps one fact true after each step: best is the first value, among the numbers visited so far, with the highest count. A number only takes over when its count is higher than every earlier number's, so the earliest of equal counts survives. When the loop ends, every number has been visited.

    Edge cases and common mistakes

    • One number. Array(7) gives 7.
    • Ties. With >= in the comparison, the last of the tied values would win. For Array(2, 2, 5, 5) the answer is 2, because 2 comes first, but a loop with >= would return 5.
    • Several ties. Array(4, 4, 8, 8, 8, 4, 8) has 4 three times and 8 four times, so the answer is 8.
    • Negative numbers work as keys like any other Int, and so does 0.
    • Counting only once per value. The second loop visits repeated values several times, but a repeat can never beat itself, so it does no harm.

    Testing

    • Array(1, 3, 2, 3, 1, 3) gives 3.
    • Array(5, 2, 2, 5, 9) gives 5.
    • Array(7) gives 7.
    • Array(4, 4, 8, 8, 8, 4, 8) gives 8.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free