Find All Duplicate Numbers in an Array
Cyclic Sort
Problem
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 returnLast updated