Find All Duplicates in an Array
Question
Given an array of integers, find all the duplicates in the array and return them in an array.
Example 1
Input: [4,3,2,7,8,2,3,1]
Output: [2,3]
Solution
- ▭
- ▯
all//Find All Duplicates in an Array.py
def find_duplicates(arr):
duplicates = []
for i in range(len(arr)):
if arr[abs(arr[i])] >= 0:
arr[abs(arr[i])] = -arr[abs(arr[i])]
else:
duplicates.append(abs(arr[i]))
return duplicates
arr = [1,2,3,2,4,5,3]
print(find_duplicates(arr)) # Output: [2,3]
all//Find All Duplicates in an Array.py
def find_duplicates(arr):
duplicates = []
for i in range(len(arr)):
if arr[abs(arr[i])] >= 0:
arr[abs(arr[i])] = -arr[abs(arr[i])]
else:
duplicates.append(abs(arr[i]))
return duplicates
arr = [1,2,3,2,4,5,3]
print(find_duplicates(arr)) # Output: [2,3]