AlgoViz

Highest Occurring Element in an Array

Easy

Tally, then take the max

Problem

Return the element that appears most often (and/or least often) in the array.

In simple words

Count everyone in a hash map, then pick the value with the tallest tally.

The idea

Build the frequency map in one pass, then scan the map once tracking the largest (and smallest) count. Scanning the map rather than the array means the second pass is over distinct values only.

The trick

  • Track max and min together in the same scan — there is no reason to do two.
  • Decide the tie-break rule up front: smallest value, first seen, or any.
1
2
2
3
2
1
0
1
2
3
4
5

Step 1 of 5. Brute force: count each number and keep the one that appears most. Values: 1, 2, 2, 3, 2, 1.

1/5
Brute force
timeO(n²)spaceO(1)

Count each number.

1for (let i = 0; i < n; i++) {2  let count = 0;3  for (let j = 0; j < n; j++) if (nums[j] === nums[i]) count++;4  if (count > best) { best = count; ans = nums[i]; }5}

Input

array
[1, 2, 2, 3, 2, 1]

Memory

count

Output

count
best
answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
nums = [1, 2, 2, 3, 2]
Output:
2
Explanation:
2 appears three times, more than anyone else.

Example 2

Input:
nums = [4, 4, 5, 5, 5]
Output:
5
Explanation:
5 wins with three appearances.

Example 3

Input:
nums = [7, 7]
Output:
7
Explanation:
7 is the most (and only) frequent.

Practice this problem:GeeksforGeeks(opens in a new tab)

Finished the walkthrough? Add it to your streak.