You are handed an array of length n where every stored value lies between 1 and n. Some values show up exactly twice while the rest show up exactly once. Return every value that appears twice.
The interesting twist is doing this without extra bookkeeping proportional to the input. Because the values themselves are valid indices, the array can double as its own visited-marker: flipping the sign at the slot a value points to records whether that value has been seen before.
Example 1
Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]
Both 2 and 3 occur twice; every other number occurs once, so only 2 and 3 are reported.
Example 2
Input: nums = [1,1,2]
Output: [1]
Only the value 1 shows up twice.
Constraints
n == nums.length with 1 ≤ n ≤ 10^51 ≤ nums[i] ≤ nEach element of nums appears once or twiceSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI