Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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
Example 1:
Input: nums = [4,3,2,7,8,2,3,1] Output: [2,3]
Example 2:
Input: nums = [1,1,2] Output: [1]
Example 3:
Input: nums = [1] Output: []
Constraints:
n == nums.length1 <= n <= 1051 <= nums[i] <= nnums appears once or twice.Problem summary: 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
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[4,3,2,7,8,2,3,1]
[1,1,2]
[1]
find-all-numbers-disappeared-in-an-array)sum-of-distances)the-two-sneaky-numbers-of-digitville)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #442: Find All Duplicates in an Array
class Solution {
public List<Integer> findDuplicates(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
while (nums[i] != nums[nums[i] - 1]) {
swap(nums, i, nums[i] - 1);
}
}
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < n; ++i) {
if (nums[i] != i + 1) {
ans.add(nums[i]);
}
}
return ans;
}
void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
// Accepted solution for LeetCode #442: Find All Duplicates in an Array
func findDuplicates(nums []int) []int {
for i := range nums {
for nums[i] != nums[nums[i]-1] {
nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
}
}
var ans []int
for i, v := range nums {
if v != i+1 {
ans = append(ans, v)
}
}
return ans
}
# Accepted solution for LeetCode #442: Find All Duplicates in an Array
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
while nums[i] != nums[nums[i] - 1]:
nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
return [v for i, v in enumerate(nums) if v != i + 1]
// Accepted solution for LeetCode #442: Find All Duplicates in an Array
struct Solution;
impl Solution {
fn find_duplicates(mut nums: Vec<i32>) -> Vec<i32> {
let mut res: Vec<i32> = vec![];
let n = nums.len();
for i in 0..n {
let x = nums[i];
let index = (x.abs() - 1) as usize;
if nums[index] < 0 {
res.push(x.abs());
} else {
nums[index] *= -1;
}
}
res
}
}
#[test]
fn test() {
let nums = vec![4, 3, 2, 7, 8, 2, 3, 1];
let res = vec![2, 3];
assert_eq!(Solution::find_duplicates(nums), res);
}
// Accepted solution for LeetCode #442: Find All Duplicates in an Array
function findDuplicates(nums: number[]): number[] {
for (let i = 0; i < nums.length; i++) {
while (nums[i] !== nums[nums[i] - 1]) {
const temp = nums[i];
nums[i] = nums[temp - 1];
nums[temp - 1] = temp;
}
}
const ans: number[] = [];
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== i + 1) {
ans.push(nums[i]);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.