Given an array arr[]
of size n
containing integers from 0
to n-1
(inclusive), some elements may appear more than once.
Find and return all duplicate elements in the array.
Print each duplicate only once.
Input: n = 7 arr = [1, 2, 3, 6, 3, 6, 1]
Output: [1, 3, 6]
Explanation:
Numbers 1, 3, and 6 appear more than once.
Input: n = 5 arr = [1, 2, 3, 4, 3]
Output: [3]
Explanation:
Only 3
appears more than once.
function findDuplicates(arr) {
const freq = {};
const result = [];
for (const num of arr) {
freq[num] = (freq[num] || 0) + 1;
}
for (const key in freq) {
if (freq[key] > 1) result.push(Number(key));
}
return result;
}
console.log(findDuplicates([1, 2, 3, 6, 3, 6, 1])); // [1, 3, 6]
Set
(Cleaner and Concise)Time Complexity: O(n)
Space Complexity: O(n)
Set
to track seen elements.Set
to store unique duplicates.function findDuplicates(arr) {
const seen = new Set();
const duplicates = new Set();
for (const num of arr) {
if (seen.has(num)) duplicates.add(num);
else seen.add(num);
}
return Array.from(duplicates);
}
console.log(findDuplicates([1, 2, 3, 6, 3, 6, 1])); // [3, 6, 1]
Works only when elements are in the range
0
ton-1
.
arr[i]
, go to index abs(arr[i])
.-1
to mark it as visited.function findDuplicates(arr) {
const result = [];
for (let i = 0; i < arr.length; i++) {
const index = Math.abs(arr[i]);
if (arr[index] >= 0) {
arr[index] = -arr[index];
} else {
result.push(index);
}
}
return result;
}
console.log(findDuplicates([1, 2, 3, 6, 3, 6, 1])); // [1, 3, 6]
0 <= arr[i] < n
.Time Complexity: O(n)
Space Complexity: O(n)
count
of size n
initialized to 0.x
, increment count[x]
.function findDuplicates(arr) {
const n = arr.length;
const count = new Array(n).fill(0);
const result = [];
for (const num of arr) {
count[num]++;
}
for (let i = 0; i < n; i++) {
if (count[i] > 1) result.push(i);
}
return result;
}
console.log(findDuplicates([1, 2, 3, 6, 3, 6, 1])); // [1, 3, 6]
n
.Approach | Time | Space | Modifies Array | Suitable For |
---|---|---|---|---|
HashMap/Object | O(n) | O(n) | ❌ | General use |
Using Set | O(n) | O(n) | ❌ | Simple + clean |
In-place Negative Marking | O(n) | O(1) | ✅ | Arrays 0 to n-1 |
Counting Array | O(n) | O(n) | ❌ | Range-based inputs |
If the array elements are from 0 to n−1, the in-place marking method is the most optimized.
Otherwise, use the Set-based approach — it’s clean, safe, and fast.
I'm Rahul, Sr. Software Engineer (SDE II) and passionate content creator. Sharing my expertise in software development to assist learners.
More about me