Find All Duplicate Numbers in an Array

Cyclic Sort

Problem

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

For example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]

Solution

class Solution:
    def findDuplicates(self, nums: List[int]) -> List[int]:
        
        i = 0
        res = []
        
        while i < len(nums):
            j = nums[i] - 1 #getting the index nums[i] needs to be at
            if nums[i] != nums[j]:
                nums[i], nums[j] = nums[j], nums[i]
            else:
                i+=1
        for i in range(len(nums)):
            if nums[i] != i+1:
                res.append(nums[i])
     
        return res
                
#Time: O(n)
#Space: O(1) ignoring the space required to return

Last updated

Was this helpful?