#442
Medium Algorithms Find all duplicates in an array
Array Hash Table Sorting
76.8% acceptance
Jan 13, 2026
11110
445
Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears at most twice, return an array of all the integers that appears twice.
You must write an algorithm that runs in O(n) time and uses only constant auxiliary space, excluding the space needed to store the output
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn find_duplicates(mut nums: Vec<i32>) -> Vec<i32> {
let mut result = Vec::new();
for i in 0..nums.len() {
let idx = (nums[i].abs() - 1) as usize;
if nums[idx] < 0 {
result.push(nums[i].abs());
} else {
nums[idx] = -nums[idx];
}
}
result
}
}