Skip to main content

Find All Duplicates in Array

Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

Problems10 / 152
Sign in

Find All Duplicates in Array

MEDIUMArrayHash Table

Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

Example 1

Input:  nums = [4,3,2,7,8,2,3,1]
Output: [2,3]

Example 2

Input:  nums = [1,1,2]
Output: [1]
Show hint

Use the array itself as a hash map. For each number, mark its corresponding index as negative. If you encounter a negative number, it's a duplicate.

Draft saves automatically

Loading editor...

Submit also runs hidden tests
nums =
[4,3,2,7,8,2,3,1]
Expected
[2,3]
Run with your own input (JSON)