Title: Find Mode of an Integer Array using HashMap
The mode of a dataset is the value that occurs most often. In this guide, you’ll learn how to find the mode of an integer array in Java using a HashMap to count occurrences in a single pass.
This problem shows up often in interviews because it tests whether you can trade memory for speed. We’ll walk through the brute-force idea first, then build an efficient HashMap-based solution, trace it on a sample input, and cover the edge cases an interviewer will expect you to raise on your own.
Understanding the Problem
Given an integer array numbers, the mode is the element that appears with the highest frequency. If more than one element shares the highest frequency, we’ll return the one that appears first among the tied values (a common, well-defined tie-breaking rule).
A naive approach checks, for every element, how many times it repeats in the rest of the array. That costs O(n^2) time. A HashMap lets us count every element’s frequency in one pass, then scan the counts once more to find the maximum, bringing the total cost down to O(n).
Approach / Algorithm Steps
- Create a
HashMap<Integer, Integer>to store each element as a key and its frequency as the value. - Iterate over the input array once. For each element, use
map.getOrDefault(element, 0) + 1to increment its count in the map. - Initialize
modeValueto the array’s first element andmaxCountto 0. - Iterate over the map’s entries. Whenever an entry’s count is strictly greater than
maxCount, updatemaxCountandmodeValueto that entry’s key and value. - After the scan,
modeValueholds the element with the highest frequency. - Return
modeValuealong withmaxCountif the caller needs both the value and how many times it occurred.
Java Program
import java.util.HashMap;
import java.util.Map;
public class FindModeOfArray {
public static int findMode(int[] numbers) {
if (numbers == null || numbers.length == 0) {
throw new IllegalArgumentException("Array must not be null or empty");
}
Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int number : numbers) {
frequencyMap.put(number, frequencyMap.getOrDefault(number, 0) + 1);
}
int modeValue = numbers[0];
int maxCount = 0;
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
if (entry.getValue() > maxCount) {
maxCount = entry.getValue();
modeValue = entry.getKey();
}
}
return modeValue;
}
public static void main(String[] args) {
int[] numbers = {4, 2, 4, 3, 2, 4, 1};
int mode = findMode(numbers);
System.out.println("Mode of the array: " + mode);
}
}Explanation of the Program
frequencyMapmaps each distinct value innumbersto the number of times it appears.getOrDefault(number, 0) + 1avoids a separate null check on the first sighting of each value.- The first loop runs in O(n) time because a
HashMapgives O(1) average-caseputandget. modeValueandmaxCounttrack the best candidate found so far. SeedingmodeValuewithnumbers[0]guarantees a valid return value even if every element is unique.- The second loop iterates over at most
ndistinct keys, so the whole algorithm stays O(n) overall. - Using
entry.getValue() > maxCount(strictly greater than) means the first value to reach a given frequency keeps its place, which implements the ‘first among ties’ rule.
Step-by-Step Trace
Let’s trace findMode on the input [5, 7, 5, 9, 7, 5], where the expected mode is 5 with a frequency of 3.
| Index | numbers[i] | frequencyMap before | frequencyMap after |
|---|---|---|---|
| 0 | 5 | {} | {5=1} |
| 1 | 7 | {5=1} | {5=1, 7=1} |
| 2 | 5 | {5=1, 7=1} | {5=2, 7=1} |
| 3 | 9 | {5=2, 7=1} | {5=2, 7=1, 9=1} |
| 4 | 7 | {5=2, 7=1, 9=1} | {5=2, 7=2, 9=1} |
| 5 | 5 | {5=2, 7=2, 9=1} | {5=3, 7=2, 9=1} |
After the counting pass, the second loop scans {5=3, 7=2, 9=1} and finds that key 5 has the highest value, 3, so modeValue becomes 5. At the end of the scan, modeValue holds the key whose mapped count is the maximum seen so far.
Examples
Example 1: Array with a Clear Winner
int[] numbers = {1, 1, 2, 2, 2, 3};
System.out.println(FindModeOfArray.findMode(numbers));
// Output: 2Here 2 appears three times, more than any other value, so it is unambiguously the mode.
Example 2: Array with a Tie
int[] numbers = {8, 3, 3, 8, 1};
System.out.println(FindModeOfArray.findMode(numbers));
// Output: 8 (or 3, depending on HashMap iteration order)Both 8 and 3 occur twice. Because HashMap does not guarantee iteration order, the tie-breaker in this implementation returns whichever tied key the map visits first, not necessarily the one that appeared first in the array. If the array’s insertion order must decide ties, use a LinkedHashMap instead.
Example 3: Array with All Unique Elements
int[] numbers = {10, 20, 30, 40};
System.out.println(FindModeOfArray.findMode(numbers));
// Output: 10Every element occurs exactly once, so the second loop stops updating after the very first key it visits, since every count ties at 1 and the comparison uses strict >. In this case modeValue ends up being whichever single-occurrence key the map happens to iterate to first, which is why seeding modeValue = numbers[0] matters as a sane fallback.
Common Mistakes to Avoid
These are the mistakes candidates most often make when solving this exact problem.
- Using
map.get(number)without a default – callingmap.get(number) + 1on a key that is not yet present throws aNullPointerExceptionbecausegetreturnsnullfor missing keys. UsegetOrDefault(number, 0) + 1instead. - Comparing with
>=instead of>– using>=when updatingmaxCountlets the last tied key overwrite earlier ones, silently changing which value you report as the mode. Use strict>to keep the first-seen tied value. - Forgetting to initialize
modeValue– leavingmodeValueuninitialized or defaulting it to 0 produces a wrong answer when 0 never appears in the array. Seed it withnumbers[0]so there is always a valid fallback. - Assuming
HashMapiteration order matches insertion order – relying on the order entries come out ofentrySet()to break ties gives inconsistent results across JVM runs. Use aLinkedHashMapif insertion-order tie-breaking is required. - Not handling an empty array – calling
numbers[0]on an empty array throws anArrayIndexOutOfBoundsExceptionbefore the loop even starts. Validate the array’s length first and throw a clear exception.
Edge Cases to Test
Run these inputs through findMode to confirm it behaves correctly at the boundaries.
- Empty array
- Single-element array
- All elements identical
- All elements unique
- Multiple values tied for the mode
- Array containing negative numbers
- Integer.MIN_VALUE or Integer.MAX_VALUE present
- Null array reference
Additional Considerations
The time complexity is O(n): one O(n) pass to build the frequency map and one O(k) pass over the map’s entries, where k is the number of distinct values and k ≤ n.
The space complexity is O(k) for the HashMap, since in the worst case (all elements unique) it stores one entry per element. This is the trade-off versus the O(n^2) brute-force approach, which uses O(1) extra space but is far slower on large arrays.
Negative numbers and Integer.MIN_VALUE work correctly because Integer keys in a HashMap are compared with equals and hashCode, not ordering, so there’s no overflow risk from arithmetic on the values themselves.
Interview Follow-up Questions
Once you can solve the base problem, expect an interviewer to push further with questions like these.
- What if you need all values tied for the mode, not just one? – track
maxCountas before, but collect every key whose count equalsmaxCountinto a list during (or after) the scan instead of overwriting a single variable. - What if the array is sorted? – you can find the mode in O(n) time and O(1) extra space by scanning for the longest run of equal adjacent elements, avoiding the
HashMapentirely. - What if the input arrives as a stream of unknown length? – keep the same
HashMapcounting logic, updatingmodeValueandmaxCountincrementally as each new element arrives, since there’s no need to see the whole stream before producing a running answer. - What if the array has billions of elements and does not fit in memory? – partition the data, compute local frequency maps per partition, then merge counts for matching keys across partitions (a map-reduce style approach) before taking the global maximum.
- What if you must solve this with O(1) extra space and cannot modify the input? – this generally requires the Boyer-Moore majority vote algorithm, which only works when a true majority element (appearing more than n/2 times) is guaranteed to exist; otherwise O(1) space is not achievable for the general mode problem.
Conclusion
Finding the mode of an integer array is a great example of using a HashMap to turn an O(n^2) counting problem into an O(n) one. Once the frequency map is built, finding the maximum is a simple linear scan.
Try adapting findMode to return all tied modes, or to work over a Stream<Integer> instead of an array, to deepen your understanding. You can learn more about array-based algorithms in the Arrays category.



