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
- Create the map
countswithmutableMapOf<Int, Int>(): values as keys, counts as values. - Loop over
numsand count each number. - Seen before. If
counts.containsKey(num), storecounts[num]!! + 1. - First time. Otherwise store 1.
- Start the search with
var best = nums[0]: the first number leads until something appears more often. - Loop over
numsagain, in order. - Compare counts with
>. Ifcounts[num]!! > counts[best]!!, makenumthe newbest. Strictly greater, so a tie keeps the earlier value. - 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 primitiveints.nums[0]reads the first element andfor (num in nums)loops over it. It is a different type fromArray<Int>and fromList<Int>.- Nullable lookups.
counts[num]is anInt?, since a missing key givesnull. The!!operator is safe in both places: the first loop checkscontainsKey, and in the second every number ofnumshas been counted already. - Comparing
Int?values. Without the!!,counts[num] > counts[best]doesn't compile, because anInt?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]gives7. - Ties.
[2, 5, 5, 2]gives2, since 2 shows up first. Looping over the map's keys instead ofnumswould 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]gives3.[5, 2, 2, 5, 9]gives5.[7]gives7.[2, 5, 5, 2]gives2.
