Find All Duplicates in an Array
Problem Statement
You’re a duplicate detective with an array of integers from 1 to n, where some numbers appear twice. Find all duplicates without extra space (if possible). This medium-level challenge offers a hashing twist—or a clever in-place trick!
Example
Input: nums = [4, 3, 2, 7, 8, 2, 3, 1]
Output: [2, 3] (Both appear twice)
Input: nums = [1, 1, 2]
Output: [1]
Input: nums = [1]
Output: [] (No duplicates)
Code
Java
Python
JavaScript
public class Solution {
public List findDuplicates(int[] nums) {
List result = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int index = Math.abs(nums[i]) - 1;
if (nums[index] < 0) result.add(index + 1);
nums[index] = -nums[index];
}
return result;
}
}
def find_duplicates(nums):
result = []
for num in nums:
index = abs(num) - 1
if nums[index] < 0:
result.append(index + 1)
nums[index] = -nums[index]
return result
function findDuplicates(nums) {
let result = [];
for (let num of nums) {
let index = Math.abs(num) - 1;
if (nums[index] < 0) result.push(index + 1);
nums[index] = -nums[index];
}
return result;
}
Explanation
- In-Place Insight: Use array as hash table; mark presence by negating values.
- Flow: For each num, mark its index; if already marked, it’s a duplicate.
- Example Walkthrough: [4,3,2,7,8,2,3,1] → mark 4,3,2,7,8, hit 2 again → [2,3].
- Hashing Alt: Set or map works but uses O(n) space.
- Constraint: Works because nums are 1 to n, fitting array indices.
Note
Time complexity: O(n), Space complexity: O(1) (excluding output). A space-saving sleuthing triumph!
