Foundations Counting with arrays and maps

44. Second Most Frequent Element

Medium

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]

Output: 1

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

Output: 0

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

Output: -1

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

nums = [7, 7, 2, 2, 5, 9, 9, 9]

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ 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.