Foundations Counting with arrays and maps
44. Second Most Frequent Element
You are given an array of non-negative integers nums. Count how many times each value appears. The
highest count is the largest of these counts. The second highest count is the largest count that is
strictly smaller than the highest count.
Return the value that appears the second highest count of times. If several values do, return the smallest of them. Values that share the highest count are never the answer, however many of them there are.
If every value appears the same number of times, no count is smaller than the highest. Then return -1.
Example 1
Input: nums = [6, 1, 6, 3, 1, 6, 3, 8]
1Explanation: 6 appears three times, the highest count. 1 and 3 appear twice, the second highest count. They tie, so the smaller one, 1, is the answer.
Example 2
Input: nums = [5, 2, 5, 2, 0]
0Explanation: 5 and 2 share the highest count, 2, so neither is the answer. The next count is 1, and only 0 has it.
Example 3
Input: nums = [3, 8, 3, 8]
-1Explanation: Both values appear twice, so no count is smaller than the highest.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 1050 ≤ nums[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.