Problem overview
The function mostFrequent receives an array of integers, nums, and returns the value that appears the most times. If several values tie for the most appearances, the one that appears first in nums wins. The array has at least one number.
For [5, 2, 2, 5, 9], both 5 and 2 appear twice. The 5 is at index 0 and the 2 first shows up at index 1, so the answer is 5.
Approach: two passes
The solution makes two passes over nums. The first builds a counting dictionary: each value is a key and its count is the value. The second finds the best value, using the counts that are now complete.
Ties are the interesting part. A dictionary has no useful order, so looping over the dictionary to find the maximum would settle ties arbitrarily. Instead the second pass walks nums itself. That visits the values in the order they appear, and because a new value replaces the current best only when its count is strictly greater, the first value to reach the top count keeps its place.
Step by step
- Create
countsas an empty[Int: Int]withvar. - Loop over
numswith the variablenum. - Bind the count with
if let count = counts[num]and storecount + 1. - Start new values at 1 in the
elsebranch. - Start
bestasnums[0], avar. - Walk
numsagain, notcounts, to meet values in their original order. - Replace
bestwhencounts[num]! > counts[best]!. - Return
best.
On [1, 3, 2, 3, 1, 3] the first pass leaves the counts 1 appears 2 times, 2 appears once and 3 appears 3 times. The second pass starts with best = 1 (count 2). The 3 has count 3, which is greater, so it becomes the best. Later values never exceed 3, so the function returns 3.
The solution in Swift
class Solution {
func mostFrequent(_ nums: [Int]) -> Int {
var counts = [Int: Int]()
for num in nums {
if let count = counts[num] {
counts[num] = count + 1
} else {
counts[num] = 1
}
}
var best = nums[0]
for num in nums {
if counts[num]! > counts[best]! {
best = num
}
}
return best
}
}
On the tie example [5, 2, 2, 5, 9], the counts are 5 appears twice, 2 appears twice and 9 appears once. The second pass starts with best = 5. The 2 has count 2, which is not greater than the count of 5, so the 5 stays. The 9 has count 1, so it doesn't replace it either, and the function returns 5.
Why two passes
It is tempting to find the answer in the first loop, by comparing counts as they grow. That is harder to get right with ties: a value can reach the top count later than another value that has the same final count but appeared earlier in the array. For [5, 2, 2, 5, 9], the 2 reaches count 2 at index 2, before the 5 does at index 3, even though the 5 appeared first. Counting everything first removes this problem, because the second pass compares final counts and uses the order of first appearance to settle ties.
The second loop doesn't skip repeated values. A value that appears several times is compared several times, but the comparison is cheap, and a repeat can never replace best with itself, because its count isn't greater than its own count.
Swift details
- The
!is safe here. A dictionary subscript returns an optional, and!unwraps it. Forced unwrapping crashes if the value isnil. Every number innumswas counted in the first loop, andbestis always a number fromnums, so both lookups find a key. - Shorter counting. The first loop can also be written
counts[num, default: 0] += 1, which reads a missing key as 0. The lesson writes out both cases so the optional is visible, and the result is the same. [Int: Int]()is a dictionary from integers to integers. Both the keys and the counts areInt.- Why
nums[0]. The array is never empty, so index 0 exists. On an empty array it would crash.
Complexity
Time: O(n). Each of the two loops visits every element once, and a dictionary lookup or update takes constant time on average.
Space: O(k), where k is the number of distinct values: the dictionary has one entry for each, which is at most n.
Edge cases and common mistakes
- Ties.
[5, 2, 2, 5, 9]returns 5, and[2, 5, 5, 2]returns 2: both appear twice and 2 comes first. - Using
>=in the second loop. The later value would replace the earlier one on a tie and the first-appearance rule would break. - Looping over the dictionary. It meets keys in an unpredictable order, so ties would no longer go to the earliest value.
- A single element.
[7]returns 7. - A frequent value that comes later.
[4, 4, 1, 1, 1]returns 1: the 4 comes first but appears fewer times, so the 1 replaces it.
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.[4, 4, 1, 1, 1]gives 1.
