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
- Create the counts.
scala.collection.mutable.Map[Int, Int]()in avalnamedcounts: each value ofnumsis a key and its count is the value. - First loop over
numswithfor (num <- nums). - Seen before: if
counts.contains(num), docounts(num) += 1. - First time: otherwise,
counts(num) = 1. - Pick a starting best.
var best = nums(0)is the answer until something beats it. - Second loop over
numsagain, in order. - Compare counts. If
counts(num) > counts(best), thenbest = num. Strictly greater keeps the earlier value on a tie. - 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
Intvalues, andcounts(num)reads the count of the numbernum, not a position in a list. - Safe reads.
counts(num)in the second loop never fails, because every number innumswas counted by the first loop. Reading a key that was never added would throw aNoSuchElementException. - 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 anArrayIndexOutOfBoundsException, sonums(0)relies on the lesson's promise of at least one number. valandvar.countsis aval: the map is changed, never replaced.bestis avarbecause it is reassigned.- Shorter counting. The first loop can be one line:
counts(num) = counts.getOrElse(num, 0) + 1. ForArray(5, 2, 2, 5, 9)it buildsHashMap(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:
| num | counts(num) | best afterwards |
|---|---|---|
| 5 | 2 | 5 |
| 2 | 2 | 5 |
| 2 | 2 | 5 |
| 5 | 2 | 5 |
| 9 | 1 | 5 |
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. ForArray(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)gives3.Array(5, 2, 2, 5, 9)gives5.Array(7)gives7.Array(4, 4, 8, 8, 8, 4, 8)gives8.
