List Every Number That Appears Twice
Implement findAllDuplicates
Given an array
nums of length n where every value is between 1 and n, and each value appears either once or twice, return every value that appears twice.
The array's own values are secretly valid indices into itself — that's the constraint a brute-force scan throws away. Treat each value as a pointer to a slot, and flip the sign of what's stored there the first time you visit it. A negative sign IS the "already seen" flag, so a second visit to the same slot is instantly recognizable — no hash setHash SetA collection that lets you check "have I seen this value before?" in O(1) time, normally backed by extra memory. This problem's constraints let the input array itself play that role. required, and the whole scan finishes in a single O(n) pass.
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: []
+ 7 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ n = nums.length ≤ 10⁵ - ●
1 ≤ nums[i] ≤ n - ●
Each integer appears once or twice — never more
nums =
[4, 3, 2, 7, 8, 2, 3, 1]