Quick revision
The short answer
Finding the values that occur more than once is an arrays and hashing problem: remember what you have already seen. We scan the array once with a HashSet; add returns false when a value is already there, and that value goes into a second, ordered set so each repeat is reported once. That is O(n) time and O(n) space, and for values in 1..n, marking slots by negating them needs only O(1) extra space.
The solution
What it costs
| Approach | Time | Extra space | Limits |
|---|---|---|---|
| Compare with every earlier position | O(n^2) | O(1) beyond the answer | none |
| Sort, then compare neighbours | O(n log n) | O(1) if sorting in place | changes the order |
| One pass with a hash set | O(n) average | O(n) | none |
| Mark slots by negating | O(n) | O(1) | values in 1..n, changes the array |
What to remember
We found the repeated values by walking the array once while a hash set remembered every value we had met. A false result from add marks a repeat, and a second, ordered set reports each repeat once, in the order it first repeated. That is O(n) time and O(n) space, and when the values lie in 1..n, marking each value's own slot by negating it does the same job in O(1) extra space. The clue to remember is that every element asks have I seen this before: when it does, keep a hash set and replace the comparison of all pairs with one pass.
1Spotting the guests who came twice
Imagine you are standing at the door of a hall with a notebook, and people arrive one at a time with a name badge. Your job is to say which names turn up more than once. The natural way is to write each name in the notebook as the person walks in. When a new person arrives, you glance at the notebook first. If the name is already there, this is a repeat, and you note it on a separate line headed repeats. If it is not there, you write it down and let them in.
That is our whole problem, and you already know how to solve it with a notebook. We are given an array of whole numbers, and we must report every value that occurs at least twice. Each number is a guest arriving at the door, and the notebook is the memory of what we have already seen. The only real question for a computer is how to make the glance at the notebook fast.
Let us keep one example for the whole article: [4, 3, 2, 7, 8, 2, 3, 1, 3]. Go through it by hand, left to right. 4, 3, 2, 7 and 8 are all new, so they go into the notebook. Then 2 arrives, and 2 is already written down, so 2 is a repeat. Then 3 arrives, and 3 is a repeat too. 1 is new. The last 3 is a repeat again, but 3 is already on the repeats line, so we do not write it twice. The answer is [2, 3].
Positions 5, 6 and 8 hold a value we have already met earlier in the array.
- length
- 9
- answer
- [2, 3]
12 appears at positions 2 and 5, and 3 at positions 1, 6 and 8. Every other value appears once, so the answer is [2, 3], each repeated value named once.
What to assume
- Should a value that appears three times, like our 3, be reported once or twice?
- Once, because the question asks which values repeat, not how many extra copies there are.
- In what order?
- We will report each value in the order it first repeats, so 2, which repeats at position 5, comes before 3, which repeats at position 6.
- Do we need the counts as well?
- Not in this version.
- What range can the values take, and may we change the array?
- We assume any int values.
A careful candidate asks a few questions first. Should a value that appears three times, like our 3, be reported once or twice? Once, because the question asks which values repeat, not how many extra copies there are. In what order? We will report each value in the order it first repeats, so 2, which repeats at position 5, comes before 3, which repeats at position 6. Do we need the counts as well? We will show a small variant that returns them. What range can the values take, and may we change the array? For any int values we will use extra memory; if the values are known to lie between 1 and n, there is a neat trick that needs none, and we will meet it too.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise an arrays and hashing problem
A beginner reading this question for the first time often thinks of comparing numbers with each other. Take the first number and look for it in the rest of the array, then take the second, and so on. That is a fair instinct, and it is the brute force we will write next. But it treats the array as a pile of pairs, when the question is really about memory.
So let us take the clues one at a time. The first clue is the phrase occur more than once. Read it from the point of view of a single element. Every element is really asking one small question: has my value appeared before me? That is a question about what we have already seen, and the fastest way to answer questions about what we have seen is to remember it as we go.
The second clue is that we only care whether two values are equal. We never ask which is bigger, or how far apart they are. Questions about equality are exactly what a hash set is built for. A hash set is a collection that stores values and can tell you whether a value is in it almost instantly, however many values it holds, a bit like the index at the back of a book, which takes you straight to the page instead of making you read every page.
The third clue is what the question does not say. It does not say the array is sorted, so we cannot rely on equal values sitting next to each other, and it does not ask for pairs that add up to anything, so two pointers have nothing to work with.
Together these clues point to the arrays and hashing pattern. The name means walking an array once while a hash set or hash map remembers what we have met, so that each element's question is answered in about one step instead of a scan. The rule to carry to new problems is that whenever each element asks have I seen this before, or how many times so far, keep a hash set or hash map and turn a comparison of all pairs into a single pass. Two sum, the first unique character and contains duplicate all follow the same rule.
Two neighbours look similar. Sorting also finds repeats, because it puts equal values side by side, but it costs O(n log n) time and changes the order. And when the values lie in a small known range, the array itself can act as the notebook, with each value's own position as its line in the book; that is the in-place trick we will see later.
3The honest first attempt, comparing each number with the ones before it
The honest first attempt does what the doorman would do without a notebook: for each new guest, look back at every guest who came earlier. In code, for each position i, we look at every earlier position j, and if a[j] equals a[i], then a[i] has appeared before. We must also be careful not to report the same value twice, so before adding it to the answer we check that it is not already there. This is a good start, because it is easy to believe it is correct.
Let us run it by hand on [4, 3, 2, 7, 8, 2, 3, 1, 3]. For the first five numbers the inner loop finds nothing, after 0, 1, 2, 3 and 4 comparisons. At position 5, the value 2 is found at position 2 after three comparisons, so 2 is reported. At position 6, the value 3 is found at position 1 after two comparisons. At position 7, the value 1 is compared with all seven earlier values and found nowhere. At position 8, the value 3 is found again after two comparisons, but it is already in the answer.
Now let us count. On the example the inner loop made 24 comparisons. In the worst case, when no value repeats, position i compares with all i earlier positions, so the total is 0 + 1 + 2 + ... + (n - 1), which is n(n - 1) / 2. For our nine numbers that would be 36, and for 100,000 numbers it is about five billion. Because that grows like n squared, we write the time as O(n squared), read as order n squared. The extra space is only the answer list, plus the out.contains check, which itself scans the answer.
So where is the waste? Look at position 7. To learn that 1 is new, we compared it with 4, 3, 2, 7, 8, 2 and 3, seven values we had already looked at. Every new position re-reads the whole history, because the brute force keeps no notebook. It knows only how to look, never how to remember.
That suggests the question that leads us on. What if we wrote each value down the first time we met it, in a place where checking for a value takes one step instead of a scan?
4Getting to one pass with a set, one observation at a time
The notebook we want is a HashSet, Java's hash set. Inside, it keeps the values in many small buckets and uses a calculation on the value, called its hash, to go straight to the one bucket where that value would live. So checking whether 2 is present does not mean reading every value; it means jumping to one bucket and looking. That takes O(1) time on average, read as constant time, whatever the number of values stored.
Now we walk the array once. For each value x we ask the set whether it has seen x. If not, we add x. If it has, x is a repeat. A beginner may write this as if (seen.contains(x)) ... else seen.add(x), and that works. But Java's add already does both jobs: it returns true when x was new and has just been added, and false when x was already there. So the single call seen.add(x) both checks and records, and a false result is our signal that x is a duplicate.
Here a beginner usually gets stuck on the value 3, which appears three times. When the second 3 arrives, add returns false and we report 3. When the third 3 arrives, add returns false again. Would we report 3 twice? If the answer were a plain list, yes, and that is the most common mistake in this problem. So we put repeats into a second set, called reported. Adding 3 to a set that already holds 3 changes nothing, which is exactly what we want.
There is one more detail, the order of the answer. A plain HashSet keeps no order. We promised to report values in the order they first repeat, so reported is a LinkedHashSet, a set that also remembers the order in which values were added. When we turn it into a list, 2 comes before 3.
Why is this correct? When we reach position i, the set holds exactly the values at positions 0 to i - 1. So add returns false exactly when a[i] appeared earlier, which is the definition of a repeat, and reported collects each such value once. For a different shape of answer, a LinkedHashMap from value to count gives the counts as well, and we will see it in the code.
Now a second road, for a special case the interviewer often raises next. Suppose the values are known to lie between 1 and n, where n is the length of the array. Then we do not need a set at all. Think of a row of n numbered lockers, one per possible value. Value v owns locker v, which is array position v - 1. When we meet v, we put a chalk mark on its locker by making the number stored there negative. If the locker is already marked, we have met v before. Here is that idea on [4, 3, 2, 7, 8, 2, 3, 1].
Only for values in 1..n. A negative number means: the value that owns this slot has been met. Dimmed cells are marked slots.
- rule
- v owns slot v - 1
- found
- []
1The values lie in 1..8 and there are 8 slots, so value v owns slot v - 1, like a numbered locker. No slot is marked yet.
- v
- 4
- slot v - 1
- 3
- found
- []
2At i = 0 we read 4, so we look at slot 3. It holds a positive number, so 4 is new, and we make that slot negative to mark it.
- v
- 3
- slot v - 1
- 2
- found
- []
3At i = 1 we read 3, so we look at slot 2. It holds a positive number, so 3 is new, and we make that slot negative to mark it.
- v
- 2
- slot v - 1
- 1
- found
- []
4At i = 2 we read 2 and look at slot 1. It holds 3, which is positive, so 2 is new, and we make slot 1 negative. Slot 2 is already negative, so we read it with
Math.abs.- v
- 7
- slot v - 1
- 6
- found
- []
5At i = 3 we read 7, so we look at slot 6. It holds a positive number, so 7 is new, and we make that slot negative to mark it.
- v
- 8
- slot v - 1
- 7
- found
- []
6At i = 4 we read 8, so we look at slot 7. It holds a positive number, so 8 is new, and we make that slot negative to mark it.
- v
- 2
- slot v - 1
- 1
- found
- [2]
7At i = 5 we read 2. Slot 1 is already negative, so we have met 2 before, and 2 is a duplicate.
- v
- 3
- slot v - 1
- 2
- found
- [2, 3]
8At i = 6 we read 3. Slot 2 is already negative, so we have met 3 before, and 3 is a duplicate.
- v
- 1
- slot v - 1
- 0
- found
- [2, 3]
9At i = 7 we read 1 and mark slot 0. The pass is over, and the two values whose slots were already marked, 2 and 3, are the duplicates.
Two details make the marking trick work. First, we read each value with Math.abs, because the position we are reading may itself already have been marked negative, as happened at position 2. Second, the mark only changes the sign, so the original value is still there under the minus sign. The price is that the array is changed; if the caller needs it, we flip the signs back afterwards. This version uses O(1) extra space, but only works for values from 1 to n.
5Watching the set version on the example
The picture below plays the set version on [4, 3, 2, 7, 8, 2, 3, 1, 3]. The pointer i shows the position we read, cells already read are marked done, and a cell is marked as found when its value turns out to be a repeat. The panel shows x, what seen.add(x) returned, the values remembered so far, and the values reported.
Watch the second row of the panel. It says true while values are new and false the moment a value comes back, and only a false sends anything to reported.
i is the position we read. The panel shows what add returned, the values remembered so far (listed in the order we met them), and the values reported.
- x
- 4
- seen.add(x)
- true
- seen
- {4}
- reported
- []
1We look at 4.
seen.add(4)returns true, because the set was empty, so 4 is new. The set now remembers 4.- x
- 3
- seen.add(x)
- true
- seen
- {4, 3}
- reported
- []
2We look at 3. It is not in the set, so add returns true and 3 is remembered. Still nothing to report.
- x
- 2
- seen.add(x)
- true
- seen
- {4, 3, 2}
- reported
- []
3We look at 2. Again new, so add returns true. The set now holds three values.
- x
- 7
- seen.add(x)
- true
- seen
- {4, 3, 2, 7}
- reported
- []
4We look at 7, another new value. add returns true and the set grows to four values.
- x
- 8
- seen.add(x)
- true
- seen
- {4, 3, 2, 7, 8}
- reported
- []
5We look at 8, also new. Five values have been seen once each, and the report is still empty.
- x
- 2
- seen.add(x)
- false
- seen
- {4, 3, 2, 7, 8}
- reported
- [2]
6We look at 2 for the second time. It is already in the set, so add returns false, and that false is our signal: 2 goes into reported.
- x
- 3
- seen.add(x)
- false
- seen
- {4, 3, 2, 7, 8}
- reported
- [2, 3]
7We look at 3 again. add returns false, so 3 is a repeat too and joins reported after 2.
- x
- 1
- seen.add(x)
- true
- seen
- {4, 3, 2, 7, 8, 1}
- reported
- [2, 3]
8We look at 1, a new value, so add returns true. The set now holds six different values.
- x
- 3
- seen.add(x)
- false
- seen
- {4, 3, 2, 7, 8, 1}
- reported
- [2, 3]
9We look at 3 for the third time. add returns false, but 3 is already in reported, so adding it there changes nothing.
- seen
- {4, 3, 2, 7, 8, 1}
- reported
- [2, 3]
- answer
- [2, 3]
10The loop is over. reported holds 2 and 3, in the order each first repeated, and the method returns the list [2, 3].
Let us read the important frames back. In the first five frames every add returns true, and the set grows by one value each time. Nothing is reported, and no earlier value is ever re-read, which is the difference from the brute force.
In the sixth frame, x is 2, and the set already holds 2 from position 2. add returns false without changing the set, so 2 goes into reported. The seventh frame does the same for 3. Check for yourself that seen still holds five values in both frames, because nothing new was added.
The ninth frame is the one that matters for the most common mistake. The third 3 makes add return false once more, but reported already holds 3, so it stays [2, 3]. With a plain list, we would have returned [2, 3, 3].
6The complete Java program
Here is the full program, with three methods: the set version, a counting version, and the marking version for values in 1..n. main runs all three on the example, and an array with no repeats, and each comment shows what that line prints.
Let us read duplicates in the order it runs. We create seen, a HashSet, to remember every value we meet, and reported, a LinkedHashSet, to collect repeats once each in order. The loop reads each x in turn. The expression !seen.add(x) does the check and the insert in one call, and it is true only when x was already present, so only then do we add x to reported. At the end, new ArrayList<>(reported) turns the set into a list, [2, 3].
repeatCounts answers the related question of how often each repeated value occurs. counts.merge(x, 1, Integer::sum) puts 1 for a value seen for the first time and adds 1 to it otherwise. Afterwards, counts.values().removeIf(c -> c < 2) throws away the values seen only once. The map is a LinkedHashMap, which keeps the order of first appearance, and 3 first appeared before 2, so it prints {3=3, 2=2}.
duplicatesInRange is the locker trick from the picture. For each position it reads v with Math.abs, looks at a[v - 1], reports v if that slot is already negative, and otherwise makes it negative. So main prints [2, 3], then {3=3, 2=2}, then [] for [1, 2, 3], then [2, 3] for the marking version.
7How much it costs, and the cases at the edges
Let us count on the example first. The set version made nine calls to add, one per element, and three calls to reported.add, one for each false. Each call takes O(1) time on average, so for n elements the time is O(n). The sets hold at most n values, so the extra space is O(n). In Java those values are stored as Integer objects, so for tens of millions of numbers the memory is noticeable, and sorting may then be the better trade.
The marking version reads each position once and changes one sign, also O(n) time, but with O(1) extra space, because it uses the array itself as its notebook.
| Approach | Time | Extra space | Limits |
|---|---|---|---|
| Compare with every earlier position | O(n^2) | O(1) beyond the answer | none |
| Sort, then compare neighbours | O(n log n) | O(1) if sorting in place | changes the order |
| One pass with a hash set | O(n) average | O(n) | none |
| Mark slots by negating | O(n) | O(1) | values in 1..n, changes the array |
Now the edges. An empty array, or one with no repeats such as [1, 2, 3], makes add return true every time, so reported stays empty and we return [], as main shows. A value repeated many times is reported once, thanks to the second set. Negative numbers and zero are fine in the set version, because a set does not care what the values are.
The marking version is different. It needs every value to lie between 1 and n, because v - 1 must be a valid position; a 0 would ask for position -1 and throw an exception. That is why we choose it only when the interviewer says the values are in that range.
8Follow-up questions
What if the array is read-only, the values are in 1..n, and exactly one value repeats?
This is the find-the-duplicate-number problem, with n + 1 values in 1..n. We may not mark the array, so we treat each value as an arrow to the position with that number. Because two positions hold the same value, two arrows point to the same place, and following the arrows from position 0 runs into a loop whose entrance is the duplicate. Floyd's method, with one slow and one fast walker, finds that entrance in O(n) time and O(1) space without changing anything.
Why not call contains and then add?
It gives the right answer, but it looks up every value twice, once to check and once to insert. add already tells us, through its true or false result, whether the value was present, so one call does both jobs. It is a small saving, but interviewers notice when you know the library this well.
How would you find values that appear in two huge files that do not fit in memory?
We split each file into smaller bucket files using a hash of each value, so equal values from both files always land in buckets with the same number. Then we load one pair of matching buckets at a time, which does fit in memory, and use a hash set as before. Another way is to sort both files on disk and walk them together. Either way each file is read only a few times.
9Conclusion
We found the repeated values by walking the array once while a hash set remembered every value we had met. A false result from add marks a repeat, and a second, ordered set reports each repeat once, in the order it first repeated. That is O(n) time and O(n) space, and when the values lie in 1..n, marking each value's own slot by negating it does the same job in O(1) extra space. The clue to remember is that every element asks have I seen this before: when it does, keep a hash set and replace the comparison of all pairs with one pass.
Open with
I will report each repeated value once, in the order it first repeats, so for 4, 3, 2, 7, 8, 2, 3, 1, 3 the answer is 2 and 3, and an array without repeats gives an empty list.
Then, if they want more
Comparing each element with every earlier one works but is O(n squared). Since every element is really asking whether its value has appeared before, I use a hash set.
I walk the array once and call seen.add on each value. add returns false when the value is already in the set, so a false tells me it is a repeat, without a separate contains call.
To report a value that appears three times only once, I put repeats into a second set, and I make it a LinkedHashSet so the order of first repetition is kept. That is O(n) average time and O(n) space. If I also need counts, a LinkedHashMap with merge gives them.
If the interviewer says the values lie in 1 to n, I can avoid the extra memory: for each value v I look at position v minus 1, report v if that slot is already negative, and otherwise make it negative, which is O(n) time and O(1) extra space but changes the array.
About this answer
- Last updated
- 14 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 22 times in that collection. How it is counted
- Official documentation
- LinkedHashMap (Java 21), HashSet (Java 21), ArrayList (Java 21), java.util, package documentation
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 "Identify the values that occur more than once in an array.": https://scrivio-interview-library.netlify.app/data-structures/solutions/identify-the-values-that-occur-more-than-once-in-an-array-57e601/