Foundations Counting with arrays and maps

43. Most Frequent Element

Medium

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]

Output: 5

Explanation: 5 appears three times, −1 twice and 8 once.

Example 2

Input: nums = [9, -4, 9, -4, 2]

Output: -4

Explanation: 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]

Output: -7

Explanation: 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.

nums = [6, 4, 6, 4, 4, 6, 1, 1]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.