Scrivio Interview library
Arrays and hashingHashing and hash mapsReported 16 times · 16 min read · updated 15 November 2026

Explain an algorithm that counts how often each element appears in an array.

1What it means to count every value in an array

Picture a class election counted on a blackboard. The teacher reads the ballots one by one. When a name is read for the first time, she writes it on the board with one stroke beside it. When a name comes up again, she finds it on the board and adds another stroke. When the last ballot is read, the strokes beside each name are its votes. Nobody reads a ballot twice. Counting how often each value appears in an array is that same job, and it is a smaller problem than it first looks.

In the question we are handed an array, a row of numbers kept side by side in memory, and we must report how many times each different value occurs. The values are the names on the ballots, and the array is the pile of ballots. What we hand back is a set of pairs, each value with its count, the way the board holds each name with its strokes.

Let us keep one example for the whole article, the array 3, 1, 3, 2, 1, 3. Before reading on, count it yourself on paper. Read the numbers from the left. The 3 is new, so write 3 with one stroke. The 1 is new, so write 1 with one stroke. The next 3 is already on your paper, so add a stroke to it. The 2 is new. The 1 gets a second stroke, and the last 3 gets a third. You should end with 3 three times, 1 twice and 2 once.

PictureThe example array and the counts we expect

Six positions, three different values. The panel shows the answer we will build.

  1. 301132231435
    3 appears
    3 times
    1 appears
    2 times
    2 appears
    1 time

    1The array 3, 1, 3, 2, 1, 3 has six positions. Counting by hand gives 3 three times, 1 twice and 2 once.

What to assume

Can the values be negative, or very large?
We assume yes, any int at all.
In what order should the counts be reported?
The question does not say, so we report them in the order each value first appears.
And what about an empty array?
It has no values, so the answer is an empty set of counts.

A careful candidate asks a few questions before writing code. Can the values be negative, or very large? We assume yes, any int at all, which matters later. In what order should the counts be reported? The question does not say, so we report them in the order each value first appears, which is how the blackboard filled up. And what about an empty array? It has no values, so the answer is an empty set of counts.

2How to recognise a counting problem that wants a hash map

A beginner reading this for the first time usually thinks of loops, because loops are what we know. For each value, go through the array and count how many times it appears. That is a reasonable first thought, and we will try it in the next section. But first let us read the question slowly.

The first clue is the phrase how often each element appears. We are not asked whether something exists, or where it is, but for a number attached to every different value. That means we need somewhere to keep a running count for each value while we read, just as the teacher needs the board. Whenever a problem says each, how many or how often, it is asking us to remember something about every value we have seen.

The second clue is the word array, with nothing said about it being sorted. In an unsorted array, equal values can sit anywhere, far apart. So when we read a value we need to find its running count at once, without searching. On the blackboard the teacher's eye jumps to the name. In a program the tool that jumps straight to the entry for a key is a hash map. A map, in everyday words, is a table of pairs, each pair a key and a value, like a word and its meaning in a dictionary. Here the key is the array value and the value stored with it is its count.

These clues together point to the arrays and hashing pattern, which pairs one pass over an array with a hash map that remembers what we have seen. Hashing is the trick that makes the map fast. The map turns each key into a number called a hash code and uses that number to choose a slot, much as the first letter of a surname tells a clerk which drawer of a filing cabinet to open. Because the slot is computed rather than searched for, finding a key takes about the same short time however many keys the map holds. The rule to carry to new problems is this. When you must count, group or remember values while walking an array, keep a hash map keyed by the value and touch each element once.

Some patterns look similar but do not fit as well. Sorting the array first would put equal values next to each other, and then one scan could count each run of equal values. That works, but sorting costs more than one pass and loses the order of first appearance. A plain counting array, where position v holds the count of value v, is faster still, but only when the values are small and never negative, which we have not been promised.

3The honest first attempt, a second scan for each value

Let us write down the first idea properly, because it is correct, easy to check and the natural place to start. For each position i, we count how many positions from i onwards hold the same value. To avoid reporting the same value twice, we keep a second array of true and false flags called counted, and once a position has been counted, we skip it when the outer loop reaches it.

Step throughA second scan for every new value

Compared cells are read by the inner loop. Found cells match the value being counted. Dim cells were counted earlier and are skipped.

  1. 301132231435i
    counting
    3
    count
    3
    comparisons
    6

    1At i = 0 the inner loop compares all six positions with 3. Positions 0, 2 and 5 match, so 3 appears 3 times. That is 6 comparisons.

  2. 301132231435i
    counting
    1
    count
    2
    comparisons
    11

    2At i = 1 the inner loop compares five positions with 1, reading the 3s again. Positions 1 and 4 match, so 1 appears 2 times.

  3. 301132231435i
    counting
    skipped
    comparisons
    11

    3Position 2 was already counted with the 3s, so the outer loop skips it without comparing anything.

  4. 301132231435i
    counting
    2
    count
    1
    comparisons
    14

    4At i = 3 the inner loop compares the last three positions with 2. Only position 3 matches, so 2 appears once. The total is 14 comparisons.

  5. 301132231435i
    3 appears
    3 times
    1 appears
    2 times
    2 appears
    1 time
    comparisons
    14

    5Positions 4 and 5 were counted earlier and are skipped. Every value is reported, but the last 3 was read three times along the way.

Java
// Brute force: for each value seen for the first time, count it with a second scan.
static void printFrequencies(int[] values) {
boolean[] counted = new boolean[values.length]; // true once a position has been counted
for (int i = 0; i < values.length; i++) {
if (counted[i]) continue; // this value was counted earlier
int count = 0;
for (int j = i; j < values.length; j++) {
if (values[j] == values[i]) { count++; counted[j] = true; }
}
System.out.println(values[i] + " appears " + count + " times");
}
}

Let us run it by hand on 3, 1, 3, 2, 1, 3 and count every comparison. At i = 0 the inner loop compares all six positions with 3, finds three of them and marks them counted. At i = 1 it compares five positions with 1 and finds two. Position 2 is already counted, so we skip it. At i = 3 it compares the last three positions with 2 and finds one. Positions 4 and 5 are counted, so we skip them. The picture shows these scans.

Now let us count the cost. Our six numbers needed 6 + 5 + 3 = 14 comparisons. The worst case is an array where every value is different, because then no position is ever skipped, and the inner loop runs n times, then n - 1, and so on down to 1. That adds up to about n times n divided by two comparisons. When the work grows like the square of n, we write it as O(n squared). For a million numbers that is about five hundred billion comparisons, which would take far too long. The extra space is the counted array, one flag per position, so O(n).

So where is the waste? Look at the last 3, in position 5. It was compared with 3, then with 1, then with 2, and each time the inner loop was asking, does this number match the one I am counting? The blackboard never asks that. When the teacher reads a ballot, she adds its stroke straight away and never looks at it again. The brute force reads the array once for every different value, when one reading is enough if we can keep all the counts at the same time.

4Getting to one pass with a hash map, one observation at a time

The waste tells us what to aim for. We want to read each number once, and at that moment add one to that number's count. So we need all the counts kept side by side while we read, the way the board holds every name at once. We keep them in a hash map called counts, where each key is a value from the array and each stored value is how many times we have seen it so far.

Then the whole method is one loop. For each number v in the array, if v is not in the map yet, put it in with a count of 1. If it is already there, replace its count with the old count plus 1. When the loop ends, the map holds every different value with its final count, because each position added exactly one to exactly one count.

Here a beginner usually writes counts.put(v, counts.get(v) + 1) and asks why that is not enough. Let us try it on our first number, 3, and see. The map is empty, so counts.get(3) has nothing to return and gives back null, Java's word for no value at all. Java must turn that null into an int before it can add 1, and it cannot, so the program stops with a NullPointerException. The first sighting of every value needs its own case. Java's merge method handles both cases in one call. counts.merge(v, 1, Integer::sum) stores 1 if v is new, and otherwise combines the old count with 1 using Integer::sum, which simply adds two numbers.

A second question follows naturally. Why use a map at all, when an int array of counts, with counts[v]++ for each v, is even simpler? Try it on the edge case -5, 7, -5. counts[-5] is not a position any array has, so Java throws an ArrayIndexOutOfBoundsException. And for a value like one billion, the array would need a billion slots for a handful of numbers. The array version is excellent when we are promised small non-negative values, and the final program shows it, but the map works for every int.

Why is the map version fast? Each merge finds the key's slot from its hash code instead of searching, so each one takes about the same short time, on average, however large the map grows. Six numbers mean six merges.

5Watching the map fill up as we read the example

The picture plays the one-pass loop on 3, 1, 3, 2, 1, 3, exactly as the Java code runs it. The arrow i shows the number being read, and the panel shows the map after that number's merge. Watch how each number causes exactly one change to the map and is never read again.

Step throughCounting 3, 1, 3, 2, 1, 3 in one pass

Each frame reads one number and makes one change to the map. Earlier numbers are finished and never read again.

  1. 301132231435i
    counts
    {}

    1We start with an empty map, counts = {}, and i on the first position. Nothing has been read yet.

  2. 301132231435i
    counts
    {3=1}

    2We read 3. It is not in the map, so merge stores 3 with a count of 1.

  3. 301132231435i
    counts
    {3=1, 1=1}

    3We read 1. It is new too, so merge stores 1 with a count of 1, after 3.

  4. 301132231435i
    counts
    {3=2, 1=1}

    4We read 3 again. It is already in the map, so merge adds 1 to its count, which becomes 2.

  5. 301132231435i
    counts
    {3=2, 1=1, 2=1}

    5We read 2. It is new, so merge stores 2 with a count of 1 at the end of the map.

  6. 301132231435i
    counts
    {3=2, 1=2, 2=1}

    6We read 1 again. Its count goes from 1 to 2. No other entry is touched.

  7. 301132231435i
    counts
    {3=3, 1=2, 2=1}

    7We read the last 3. Its count goes from 2 to 3. That was the sixth and final merge.

  8. 301132231435
    counts
    {3=3, 1=2, 2=1}
    merges
    6

    8The loop ends after six merges. The map holds each value with its count, in order of first appearance.

Let us read the important frames back. In the second and third frames, 3 and 1 are new, so merge creates their entries. The fourth frame is the first repeat. The map already has 3, so merge adds 1 to its count and does not create a second entry. This is the moment the put and get version would have been fine, while in the second frame it would have crashed.

Compare the last 3 with the brute force. There it was read three times, once by each scan. Here it is read once, in the seventh frame, and its count simply moves from 2 to 3. The map ends as {3=3, 1=2, 2=1}, which is the same answer we found on paper.

6The complete Java program

Here is the complete program. frequencies is the main method. We use a LinkedHashMap, a hash map that also remembers the order in which keys were first added, so the counts come out in order of first appearance. frequenciesSmallRange is the counting array version for the case where the values are known to lie between 0 and some small maxValue. main runs our example, an array with negative numbers, an empty array, the small-range version, and finally prints the counts in the sentence form the question uses.

Java
import java.util.*;
public class CountFrequency {
// Count how often each value appears, keeping the order of first appearance.
static Map<Integer, Integer> frequencies(int[] values) {
Map<Integer, Integer> counts = new LinkedHashMap<>();
for (int v : values) {
counts.merge(v, 1, Integer::sum); // 1 if v is new, otherwise old count + 1
}
return counts;
}
// When values are known to lie in 0..maxValue, a plain array is faster still.
static int[] frequenciesSmallRange(int[] values, int maxValue) {
int[] counts = new int[maxValue + 1];
for (int v : values) counts[v]++;
return counts;
}
public static void main(String[] args) {
int[] values = {3, 1, 3, 2, 1, 3};
System.out.println(frequencies(values)); // {3=3, 1=2, 2=1}
System.out.println(frequencies(new int[] {-5, 7, -5})); // {-5=2, 7=1}
System.out.println(frequencies(new int[] {})); // {}
System.out.println(Arrays.toString(frequenciesSmallRange(values, 3))); // [0, 2, 1, 3]
// Printing in the form the question asks for:
frequencies(values).forEach((v, c) -> System.out.println(v + " appears " + c + " times"));
// 3 appears 3 times
// 1 appears 2 times
// 2 appears 1 times
}
}

Let us read frequencies in the order it runs. It first creates the empty map. The for loop then reads each number v once, from left to right. The single line inside, counts.merge(v, 1, Integer::sum), is the stroke on the blackboard. When v is new it stores 1, and when v is known it adds 1 to the old count. When the loop finishes, the method returns the map.

frequenciesSmallRange runs the same idea with an array in place of the map. new int[maxValue + 1] creates one slot for every value from 0 to maxValue, all starting at 0, and counts[v]++ adds one to the slot for v. For our example with maxValue 3 it prints [0, 2, 1, 3], which reads as no zeros, two 1s, one 2 and three 3s. Notice the slot for 0, which is easy to forget.

The last line of main uses forEach, which hands each key and its count to the small piece of code in brackets, so each pair is printed as a sentence. Printing is kept apart from counting on purpose, so the counting method can be tested and reused.

7How much it costs, and the cases at the edges

Let us count on the example first. Six numbers meant six merges, each one a hash code, a jump to a slot and one small update. In general, an array of n numbers needs n merges, and each merge takes constant time on average, so the whole method is O(n) time. We cannot do better, since every number must be read at least once. The brute force needed 14 comparisons on these six numbers and about n squared divided by two in the worst case.

The space is one map entry for each different value. If we call the number of different values k, the space is O(k), at most O(n) when every value is different. Our example has n = 6 and k = 3, so the map holds three entries.

Comparing the ways to count
ApproachTimeExtra spaceWorks for any int?
Second scan for each new valueO(n squared)O(n) flagsyes
Sort, then count runs of equal valuesO(n log n)O(1) to O(n)yes, but order of first appearance is lost
One pass with a hash mapO(n) on averageO(k)yes
One pass with a counting arrayO(n + maxValue)O(maxValue)no, only small non-negative values

Why do we say on average? A hash map relies on keys spreading out over its slots. If many keys landed in the same slot, finding one would mean searching among them. Java's HashMap guards against this by turning a crowded slot into a small sorted tree, so even a bad case stays fast, and for ordinary integers it rarely matters.

Now the edge cases. An empty array never enters the loop, and the method returns an empty map, printed as {}. Negative numbers are ordinary keys, so -5, 7, -5 gives {-5=2, 7=1}. An array where every value is the same gives one entry whose count is n. An array where every value is different gives n entries of 1, the worst case for space but still one pass. Counts cannot overflow an int unless the array has more than about two billion elements, which a Java array cannot hold.

8Follow-up questions

How would you find the value that appears most often?

We build the same map first. Then we walk through its entries once, keeping the best value and its count so far, and replace them whenever an entry has a larger count. On our example the walk sees 3 with 3, then 1 with 2 and 2 with 1, so 3 stays the best. That adds one more pass over at most n entries, so the total stays O(n) time and O(k) space.

What if the array is too large to fit in memory?

Then we read it in pieces from a file or a stream and keep updating the same map, because the map only needs one entry per different value, not the whole array. If even the map is too large, we can split the values into groups by their hash code, count each group separately, and add the results together, which is how large data systems count words across many machines.

Can you count without any extra space?

Only by giving something up. If we may change the array, we can sort it in place and count each run of equal values in one scan, using O(1) extra space with an in-place sort, but the time becomes O(n log n) and the order of first appearance is lost. If the values are known to lie between 1 and n, there are tricks that store counts inside the array itself, but they change the input and only work under that promise.

9Conclusion

We counted every value by reading the array once and keeping a hash map from each value to its count, with merge adding one to a value's count, or storing 1 the first time we meet it. Each number is read once, so it costs O(n) time on average and O(k) space for k different values. The clue to remember is the phrase how often each: whenever you must count or remember values while walking an array, reach for a hash map keyed by the value.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me check the details first. The values can be any int, including negatives, I will report each value with its count, and an empty array gives no counts.

Then, if they want more

The simple approach is, for each value I have not counted yet, to scan the rest of the array and count its matches. That is correct but O(n squared) in the worst case, when all values are different, because the same elements are compared again for every new value.

Instead I will make one pass with a hash map from value to count. For each element I call merge with 1 and Integer::sum, which stores 1 the first time and adds one after that. I avoid put with get plus one, because get returns null for a new key and unboxing it throws.

I will use a LinkedHashMap so the counts come out in order of first appearance. Each merge is constant time on average, so the whole thing is O(n) time, and the map holds one entry per distinct value, O(k) space.

If the values were known to be small and non-negative, I would use an int array of counts instead, which avoids hashing entirely.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 16 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain an algorithm that counts how often each element appears in an array.": https://scrivio-interview-library.netlify.app/data-structures/solutions/explain-an-algorithm-that-counts-how-often-each-element-appears-b65173/