Find All Duplicates in an Array – Solution & Complexity
Solution Walkthrough
Step 1: Use the problem guarantees
Every number is between
1andn, and each value appears at most twice. That means you can either count what you have seen with extra memory, or reuse the input array itself as a visitation map by jumping to indexvalue - 1.Step 2: Warm up with a hash-set solution
Scan the array once, track values already seen, and append a value when it appears the second time. Because the final answer must be deterministic and sorted, sort the collected duplicates before returning them.
Step 3: Reuse the array as the visited structure
For each value
val, look at indexabs(val) - 1. If that slot is still positive, negate it to mark thatvalhas been seen once. If that slot is already negative, thenvalis appearing for the second time, so it belongs in the answer.Step 4: Final in-place marking solution
This is the classic follow-up solution: detect duplicates in one pass by negating
nums[abs(val) - 1], collect values that hit an already-negative slot, then sort the output so the returned array is always in ascending order.