Problem overview
The method MostFrequent receives an int[] named nums and returns the value that appears the most times. If several values tie, it returns the one that shows up first in the array. The array has at least one number.
For [1, 3, 2, 3, 1, 3] the answer is 3: it appears three times, 1 twice and 2 once. For [5, 2, 2, 5, 9], both 5 and 2 appear twice, and 5 is first in the array, so the answer is 5. For [7] the answer is 7.
Approach: two passes
The work splits into two simple passes over the array.
The first pass counts. A Dictionary<int, int> maps each value to the number of times it appears. A value already in the dictionary gets 1 added, and a new value is written with the tally 1. The check with ContainsKey is needed because reading a missing key throws a KeyNotFoundException.
The second pass chooses. Start with the first number as the best, then walk through nums again and replace the best whenever a number has a strictly higher count. Walking nums and not the dictionary matters: the loop meets the values in the order they appear in the array, so on a tie the earlier value stays as the best. The strict > is what keeps it there.
On [5, 2, 2, 5, 9] the counts are 5 with 2, 2 with 2 and 9 with 1. The best starts at 5. The loop sees 5 (not higher than itself), 2 (a tie, not higher), 2, 5 and 9 (lower), so 5 stays.
The same idea on [1, 3, 2, 3, 1, 3]: after the first pass the counts are 1 with 2, 3 with 3 and 2 with 1. The best starts at 1, which has count 2. The loop reaches 3 (count 3, higher than 2), so 3 becomes the best. Nothing after that has a count above 3, so the answer is 3. The second pass never changes the dictionary. It only reads from it, and that is why one int is enough to remember the winner.
Step by step
- Create an empty
Dictionary<int, int>namedcounts. - Write a
foreachloop overnumswith anintnamednum. - If
counts.ContainsKey(num), add 1 tocounts[num]. - Otherwise set
counts[num]to 1. It is the first time this value is seen. - Create an
intnamedbestand start it atnums[0]. The first number is the answer until a value with a higher count turns up. - Write a second
foreachloop overnums, again withnum. - Compare counts with
counts[num] > counts[best]and makenumthe newbestwhen it is true. Strictly greater, so a tie keeps the first value. - Return
best.
The solution in C#
class Solution {
public int MostFrequent(int[] nums) {
Dictionary<int, int> counts = new Dictionary<int, int>();
foreach (int num in nums) {
if (counts.ContainsKey(num)) {
counts[num] += 1;
} else {
counts[num] = 1;
}
}
int best = nums[0];
foreach (int num in nums) {
if (counts[num] > counts[best]) {
best = num;
}
}
return best;
}
}
Details worth knowing:
- Inside the second loop,
counts[num]andcounts[best]are always safe to read, because the first loop added every value ofnums. - Both loops use a variable named
num. That is allowed because each loop variable lives only inside its own loop. - The method returns a value from
nums, not its count. Don't returncounts[best].
Complexity
Each pass visits the n numbers once, and each dictionary operation takes constant time on average, so the time is O(n). The dictionary has one entry per distinct value, so the space is O(k) for k distinct values, at most n.
A slower way to the same answer is to count each value with a nested loop, which takes O(n²) time. Another is to sort a copy of the array and measure runs of equal values, which takes O(n log n) time, but sorting loses the order of first appearance, so settling ties would need extra bookkeeping. The dictionary keeps the counting simple and the tie rule easy to apply.
Edge cases and common mistakes
- Ties. With
>=in the second loop, the last of the tied values would win, and[5, 2, 2, 5, 9]would give 2. Walkingcounts.Keysinstead ofnumswould not promise the first-appearance order either. - One element. The array
[7]never changesbest, which is already 7. - Negative numbers and zero. They work as keys like any other
int. - Returning the count. The answer is the value, not how many times it appears.
Testing
| nums | Result |
|---|---|
[1, 3, 2, 3, 1, 3] | 3 |
[5, 2, 2, 5, 9] | 5 |
[7] | 7 |
Try also an array where every value is different, such as [4, 8, 6]. All the counts are 1, no value is ever strictly higher than the best, and the method returns the first number, 4. Each of the first two rows above comes from the tie rule or the count: in the first, 3 wins on count, and in the second, 5 wins because it comes first.
