Start learning free

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

Most Frequent Element in Kotlin: Count, Then Pick

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

    KOTLIN · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Most Frequent Element in Kotlin, explained

    Problem overview

    The function mostFrequent receives an IntArray, nums, and returns the value that appears the most times. If several values tie, it returns the one that shows up first in nums. For [1, 3, 2, 3, 1, 3] the answer is 3, which appears three times. For [5, 2, 2, 5, 9], both 5 and 2 appear twice, and 5 comes first, so the answer is 5.

    Approach: two passes

    The first pass builds a map from each value to its count. The second pass looks for the best value, and it walks nums itself rather than the map. That choice settles ties: nums meets the values in the order they first appear, and the search keeps the current best unless a value has a strictly higher count. Among values with the same count, the earliest one stays in front.

    Step by step

    1. Create the map counts with mutableMapOf<Int, Int>(): values as keys, counts as values.
    2. Loop over nums and count each number.
    3. Seen before. If counts.containsKey(num), store counts[num]!! + 1.
    4. First time. Otherwise store 1.
    5. Start the search with var best = nums[0]: the first number leads until something appears more often.
    6. Loop over nums again, in order.
    7. Compare counts with >. If counts[num]!! > counts[best]!!, make num the new best. Strictly greater, so a tie keeps the earlier value.
    8. Return best.

    The solution in Kotlin

    class Solution {
        fun mostFrequent(nums: IntArray): Int {
            val counts = mutableMapOf<Int, Int>()
            for (num in nums) {
                if (counts.containsKey(num)) {
                    counts[num] = counts[num]!! + 1
                } else {
                    counts[num] = 1
                }
            }
            var best = nums[0]
            for (num in nums) {
                if (counts[num]!! > counts[best]!!) {
                    best = num
                }
            }
            return best
        }
    }
    

    Kotlin details worth knowing:

    • IntArray. It is Kotlin's array of primitive ints. nums[0] reads the first element and for (num in nums) loops over it. It is a different type from Array<Int> and from List<Int>.
    • Nullable lookups. counts[num] is an Int?, since a missing key gives null. The !! operator is safe in both places: the first loop checks containsKey, and in the second every number of nums has been counted already.
    • Comparing Int? values. Without the !!, counts[num] > counts[best] doesn't compile, because an Int? can't be compared with >.
    • The second pass repeats work. A value that appears several times is compared several times. It does no harm: the later comparisons find the same count and change nothing.

    Tracing the example

    For [5, 2, 2, 5, 9], the first loop leaves this map:

    {5=2, 2=2, 9=1}

    The second loop starts with best = 5 (the first number) and compares each number's count with the count of best:

    5 -> best=5
    2 -> best=5
    2 -> best=5
    5 -> best=5
    9 -> best=5

    The number 2 has a count of 2, equal to the count of 5, so it doesn't pass the strict comparison. The number 9 has a count of 1 and loses. The answer is 5.

    Why not one pass?

    A single loop could track the best while it counts, but then a value's count is still growing when it is compared, and the tie rule becomes harder to get right. Two passes keep each job simple: the first loop only counts, the second only chooses. The cost is one extra walk over the array, which doesn't change the O(n) total.

    Both loops over nums also mean that tie-breaking needs no extra data: the array already stores the values in the order that decides the tie.

    Complexity

    Time: O(n). Each pass visits every number once, and map lookups and updates take constant time on average.

    Space: O(k), where k is the number of different values, at most n, for the map.

    Both loops are plain for loops over the same array, so the function reads top to bottom as "count everything, then choose".

    Edge cases and common mistakes

    • One number. [7] gives 7.
    • Ties. [2, 5, 5, 2] gives 2, since 2 shows up first. Looping over the map's keys instead of nums would make the tie depend on the map's order, and using >= would make the later value win.
    • Returning the count. The answer is the value (3 in the first example), not how often it appears.
    • Negative numbers and zero. They are ordinary keys, so they need no special handling.

    Other ways to solve it

    The brute-force version counts each value by scanning the whole array for it, which costs O(n²). Sorting the array first puts equal values side by side and lets a single scan measure the runs, at O(n log n), but the original order is lost, and that order is what breaks ties here. The map keeps the whole job at O(n) and leaves nums untouched, so the tie rule stays easy to apply.

    A shorter way to count

    The if and else of the first loop can be replaced by one line, counts[num] = (counts[num] ?: 0) + 1. The Elvis operator ?: gives 0 when the key is missing, so a new value starts at 1 and a known one goes up by one. The lesson uses the longer form first because each branch can be read on its own, and because it shows why !! is needed: a lookup gives Int?.

    Testing

    • [1, 3, 2, 3, 1, 3] gives 3.
    • [5, 2, 2, 5, 9] gives 5.
    • [7] gives 7.
    • [2, 5, 5, 2] gives 2.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free