442. Find All Duplicates in an 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. You must write an algorithm that runs in O(n) time and uses only constant extra space.

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

  • code flip the coin, if already flipped, then it’s twice
class Solution:
    def findDuplicates(self, nums: List[int]) -> List[int]:
        rs = []
        for num in nums:
            num = abs(num)
            if nums[num-1] < 0:
                rs.append(num)
            else:
                nums[num-1] = -nums[num-1]
        return rs

  • code
class Solution:
    def findDuplicates(self, nums: List[int]) -> List[int]:
        res = set()
        for i in range(len(nums)):
            while nums[i] != i + 1:
                index = nums[i] - 1
                if nums[i] == nums[index]: 
                    res.add(nums[i])
                    break
                nums[index], nums[i] = nums[i], nums[index]
        return list(res)