Find All Duplicates in an Array

Source: leetcode 442. Find All Duplicates in an Array

Q. Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:
Input: [4, 3, 2, 7, 8, 2, 3, 1]
Output: [2, 3]

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @param {number[]} nums
* @return {number[]}
*/
export default function findDuplicates (nums) {
const res = []
for (let i = 0; i < nums.length; i++) {
const id = Math.abs(nums[i]) - 1
if (nums[id] < 0) {
res.push(id + 1)
}
nums[id] = -nums[id]
}
return res
}

Share Comments