Find All Duplicates in an Array (LeetCode 442): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Create an empty
resultlist. - For each
numinnums, computeindex = abs(num) - 1, taking the absolute value because the element may already have been negated. - If
nums[index] < 0, the valueindex + 1was seen earlier, so append it toresult. - Otherwise negate
nums[index]to mark the valueindex + 1as seen. - After the loop, return
result, which lists each duplicated value once.
Step-by-step example
nums = [4, 3, 2, 7, 8, 2, 3, 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].
- 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].
- The value 2 maps to index 1, where -3 is already negative, so 2 is appended to the result.
- The value -3 has absolute value 3, mapping to index 2, which holds -2, so 3 is appended as well.
- 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 result1class Solution {
2 public List<Integer> findDuplicates(int[] nums) {
3 List<Integer> result = new ArrayList<>();
4
5 for (int i = 0; i < nums.length; i++) {
6 int index = Math.abs(nums[i]) - 1;
7
8 if (nums[index] < 0) {
9 result.add(index + 1);
10 } else {
11 nums[index] = -nums[index];
12 }
13 }
14
15 return result;
16 }
17}1class Solution {
2public:
3 vector<int> findDuplicates(vector<int>& nums) {
4 vector<int> result;
5
6 for (int i = 0; i < nums.size(); i++) {
7 int index = abs(nums[i]) - 1;
8
9 if (nums[index] < 0) {
10 result.push_back(index + 1);
11 } else {
12 nums[index] = -nums[index];
13 }
14 }
15
16 return result;
17 }
18};Time and space complexity
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.
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 - 1instead ofabs(num) - 1as the index. After earlier negations,numcan be negative, which gives a negative index and in Python silently reads from the end of the array. - Appending
numinstead ofindex + 1. By the time the second occurrence is read,numitself 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.