The problem. You are given an integer array nums of length n where every value is in the range 1 to n, and each value appears once or twice. Return every value that appears twice. The follow-up asks for O(n) time and O(1) extra space.
Input: nums = [4, 3, 2, 7, 8, 2, 3, 1]
Output: [2, 3]
Input: nums = [1, 1, 2]
Output: [1]
Input: nums = [1]
Output: []The answer can be returned in any order. Keep an eye on the unusual promise — values from 1 to n in an array of length n. The best solution depends on it completely.
Compare each element with every element after it. Because a value appears at most twice, every matching pair is a different duplicate, so each one is reported exactly once.
function findDuplicates(nums) { const result = []; for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { if (nums[i] === nums[j]) result.push(nums[i]); // values appear at most twice } } return result;}Time O(n²), space O(1). The inner loop is asking one question over and over: have I seen this value before?
A hash set answers "have I seen this value?" in O(1). Walk the array once: if the value is already in the set, it's a duplicate; otherwise add it.
function findDuplicates(nums) { const seen = new Set(); const result = []; for (const x of nums) { if (seen.has(x)) result.push(x); else seen.add(x); } return result;}Time O(n), space O(n). Fast, but the set can grow to n entries, and the follow-up asks for O(1) extra space. Where else could we keep one "seen" mark per value?
Every value v is between 1 and n, so it can point at an index: its home, v − 1. That gives every possible value its own slot in the array. To mark "I've seen v", make the number stored at its home negative.
Walk the array once. For each value (read with abs, since it may already have been flipped), look at its home: if the number there is already negative, this value was seen before — it's a duplicate. Otherwise flip it to negative.
After one pass, the signs tell the whole story:
Marked (negative) cells are tinted. Watch the second 2 and the second 3 land on homes that are already marked.
Time O(n), space O(1) extra. The "seen" marks live in the signs of the input. If the caller needs the array unchanged, flip every value back to positive in a second pass — still O(n).
O(n²)Every value is compared with every later value: about n²/2 pairs.
O(1)Only two loop indexes; nothing is stored.
O(n)[3, 1, 2] returns [].[1] returns [].[2, 2] returns [2]; [1, 1, 2, 2] returns [1, 2].The same "value points at an index" trick finds the missing numbers too: after the pass, every slot that is still positive is a value that never appeared (here 5 and 6). It only works because the values are limited to 1..n — always check the constraints for that hint.
One pass, and each set lookup or insert is O(1) on average.
O(n)The set can grow to hold every value.
O(n)One pass; flipping a sign and checking it are both O(1).
O(1)The "seen" marks live in the signs of the input, so no extra structure.