Find All Numbers Disappeared in an Array

Cyclic Sort

Problem

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

Find all the elements of [1, n] inclusive that do not appear in this array.

For example:

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

Output:
[5,6]

Solution

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        #1) sort the numbers in the correct index position 
        #2) find numbers out of place 
        
        i = 0
        while i < len(nums):
            j = nums[i] - 1
            if nums[i] != nums[j]:
                nums[i], nums[j] = nums[j],nums[i]
            else:
                i+=1
        res = []
        
        for i in range(len(nums)):
            if i+1 != nums[i]:
                res.append(i+1)
        return res
        
        
#Once we are done with the cyclic sort we iterate the 
array to find all indices that are missing the correct
numbers.

Last updated