Foundations Counting with arrays and maps
43. Most Frequent Element
You are given an array of integers nums. Return the value that appears in it the most times.
Several values can share the highest count. Then return the smallest of them. For example, if 4 and −3 both appear five times and no value appears more often, the answer is −3.
Example 1
Input: nums = [5, -1, 5, 8, -1, 5]
5Explanation: 5 appears three times, −1 twice and 8 once.
Example 2
Input: nums = [9, -4, 9, -4, 2]
-4Explanation: 9 and −4 both appear twice, more often than 2. They tie, so the smaller value, −4, is the answer.
Example 3
Input: nums = [1000000000, -7, 3]
-7Explanation: Every value appears once, so all three tie, and the smallest of them is −7.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.