easyArray ProblemsJava

Find the Most Frequent Element in an Array

Return the element that occurs the most times in an integer array.

Quick Answer

Walk the array once and count each value in a HashMap<Integer, Integer>. Then scan the map (or track a running best while counting) and return the key whose count is the largest. This runs in O(n) time using O(k) extra space for k distinct values.

Problem Statement

Given an array of integers, return the element that appears the most often. If several elements share the highest frequency, returning any one of them (or the first one reached) is acceptable unless the interviewer specifies a tie rule.

For example, in [1, 3, 2, 3, 4, 3] the value 3 appears three times, more than any other value, so the answer is 3.

Input: An integer array arr of length n (n >= 1).

Output: The single integer value that occurs the most times.

Examples

Example 1
Input:  [1, 3, 2, 3, 4, 3]
Output: 3

3 appears three times; every other value appears at most once.

Example 2
Input:  [5, 5, 4, 4, 4, 2]
Output: 4

4 appears three times, beating 5 (twice) and 2 (once).

Constraints

  • 1 <= n <= 10^6
  • Values fit in a 32-bit int (may be negative)

Think Before You Code

Reveal the questions to ask yourself first
  • How do you record how many times you have seen each distinct value?
  • Can you track the current best element while you count, or do you need a second pass?
  • What should happen when two values tie for the highest count?

Hints

Open them one at a time — try after each before revealing the next.

Hint 1
You need a count per distinct value — a Map from value to its running count is the natural structure.
Hint 2
Use `map.getOrDefault(v, 0) + 1` to increment a count that may not exist yet.
Hint 3
Keep a `bestValue`/`bestCount` pair and update it whenever a value's new count exceeds `bestCount`; that avoids a second pass over the map.

Approach

Reveal the step-by-step approach

Count first, then pick the maximum.

  1. Create a HashMap<Integer, Integer> mapping value to frequency.
  2. For each element v, set count = map.getOrDefault(v, 0) + 1 and put it back.
  3. While updating, compare count against a stored bestCount; if it is larger, update bestCount and remember v as bestValue.
  4. After the loop, bestValue holds an element with the highest frequency.

Counting as you go and tracking the best in the same pass keeps it a single sweep.

Dry Run

Walk through the example step by step

Counting [1, 3, 2, 3, 4, 3] (best starts empty):

v | map after update      | count | bestValue / bestCount
--+-----------------------+-------+----------------------
1 | {1:1}                 | 1     | 1 / 1
3 | {1:1, 3:1}            | 1     | 1 / 1
2 | {1:1, 3:1, 2:1}       | 1     | 1 / 1
3 | {1:1, 3:2, 2:1}       | 2     | 3 / 2
4 | {1:1, 3:2, 2:1, 4:1}  | 1     | 3 / 2
3 | {1:1, 3:3, 2:1, 4:1}  | 3     | 3 / 3

Result: 3.

Solution

Reveal the full Java solution
import java.util.HashMap;
import java.util.Map;

public class MostFrequentElement {
    public static int mostFrequent(int[] arr) {
        Map<Integer, Integer> counts = new HashMap<>();
        int bestValue = arr[0];
        int bestCount = 0;
        for (int v : arr) {
            int count = counts.getOrDefault(v, 0) + 1;
            counts.put(v, count);
            if (count > bestCount) {
                bestCount = count;
                bestValue = v;
            }
        }
        return bestValue;
    }

    public static void main(String[] args) {
        System.out.println(mostFrequent(new int[]{1, 3, 2, 3, 4, 3})); // 3
        System.out.println(mostFrequent(new int[]{5, 5, 4, 4, 4, 2})); // 4
    }
}

The map gives O(1) average lookups, so counting every element takes O(n) total. Because we only overwrite bestValue when a count strictly exceeds the current best, the first value to reach the maximum frequency wins any tie, which keeps the result deterministic for a given input order.

Time: O(n)Space: O(k) where k is the number of distinct values

Common Mistakes

  • Initializing bestCount to a large number so the first real count never overwrites it.
  • Comparing frequencies with `>=`, which makes a later tied value replace the earlier one unexpectedly.

Edge Cases to Test

  • A single-element array should return that element.
  • All elements equal should return that value with count n.
  • Negative numbers must be counted the same way as positives.

Interview Follow-Ups

  • How would you return every element that ties for the highest frequency?
  • How would you find the k most frequent elements efficiently?
  • Could you solve it in O(1) extra space if the values were bounded to a small range?

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Explore the Java Full Stack program →
Chat with us