Find All Duplicates in an Array (LeetCode 442): Solution and Explanation

Medium
Array
Hash Table

You are given an array of length n whose values all lie between 1 and n, and each value appears either once or twice. Return every value that appears twice, using linear time and only constant extra space beyond the output.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

With no space limit, this is a one-liner: count occurrences in a hash map, or keep a set and record any value you see a second time. Sorting the array and comparing neighbors also works in O(n log n) without a map. The challenge is the constraint of O(n) time with no extra memory, which rules out all of those.

The constraint that values are between 1 and n is the hint. It means every value can be used as an index into the array itself: value v corresponds to slot v - 1. So the array can double as its own lookup table. You just need a way to record "I have seen value v" in slot v - 1 without destroying the number already stored there, because you still need to read that number later.

Flipping the sign does exactly that. All values start positive, so a negative sign can mean "the value matching this index has been seen", while abs() recovers the original number whenever you need it. Walk the array; for each number, look at slot abs(num) - 1. If it is already negative, this value was seen before, so it is a duplicate. Otherwise negate it to mark it as seen. Since each value appears at most twice, each duplicate is reported exactly once.

Approach: Sign marking with index mapping

  1. Create an empty result list.
  2. For each num in nums, compute index = abs(num) - 1, taking the absolute value because the element may already have been negated.
  3. If nums[index] < 0, the value index + 1 was seen earlier, so append it to result.
  4. Otherwise negate nums[index] to mark the value index + 1 as seen.
  5. After the loop, return result, which lists each duplicated value once.

Step-by-step example

nums = [4, 3, 2, 7, 8, 2, 3, 1]
  1. 4 marks index 3, 3 marks index 2, and 2 marks index 1. The array becomes [4, -3, -2, -7, 8, 2, 3, 1].
  2. Next comes -7, whose absolute value 7 marks index 6. Then 8 marks index 7. The array is now [4, -3, -2, -7, 8, 2, -3, -1].
  3. The value 2 maps to index 1, where -3 is already negative, so 2 is appended to the result.
  4. The value -3 has absolute value 3, mapping to index 2, which holds -2, so 3 is appended as well.
  5. Finally -1 maps to index 0, which is positive, so it is negated. The function returns [2, 3].

Code: Python, Java, C++

1class Solution:
2    def findDuplicates(self, nums: List[int]) -> List[int]:
3        result = []
4
5        for num in nums:
6            index = abs(num) - 1
7
8            if nums[index] < 0:
9                result.append(index + 1)
10            else:
11                nums[index] = -nums[index]
12
13        return result

Time and space complexity

Time

O(n)

The loop visits each element once and does constant work per element: an absolute value, one lookup and possibly a negation or an append.

Space

O(1)

Apart from the output list, the algorithm stores nothing; the seen markers live in the signs of the input array. Note that the input is modified.

Other approaches

Hash set (time O(n), space O(n))

Add each value to a set and append it to the result if it is already present. It is the clearest approach and leaves the input untouched, but it uses O(n) extra memory.

Cyclic sort (time O(n), space O(1))

Swap each value into its home slot v - 1 until every slot holds its own value or a duplicate blocks the swap. Then any slot i whose value is not i + 1 holds a duplicate. It also uses O(1) extra space and works when you cannot use the sign bit.

Common mistakes

  • Using num - 1 instead of abs(num) - 1 as the index. After earlier negations, num can be negative, which gives a negative index and in Python silently reads from the end of the array.
  • Appending num instead of index + 1. By the time the second occurrence is read, num itself may already be negative, so appending it directly puts negative values in the output.
  • Applying this to arrays where a value can appear three times. The third occurrence would see a negative marker again and report a duplicate twice.
  • Forgetting that the input is mutated. If the caller needs the original array, restore it by taking absolute values at the end.

Frequently asked questions

How can you find duplicates without extra space?

Because every value is between 1 and n, each value maps to an index. Negating the element at that index records that the value was seen, and the original number is still recoverable with abs().

Why does sign marking only work when values are between 1 and n?

Each value must map to a valid, unique index, and every element must start positive so that a negative sign unambiguously means seen. Zero or out-of-range values would break the mapping.

Does this solution modify the input array?

Yes, several entries end up negative. If that is not allowed, either restore the signs afterward or use a hash set, which costs O(n) extra memory.