Find All Numbers Disappeared in an Array

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.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

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

Output:
[5,6]

Solution

Check out my previous article, for clear understanding.

C# Program

public class Solution {
    public IList<int> FindDisappearedNumbers(int[] nums) {
        IList<int> result = new List<int>();
        for(int i=0;i<nums.Length;i++)
        {
            int index = Math.Abs(nums[i])-1;
            
            if(nums[index] > 0)
                nums[index] = nums[index] * -1;
        }
        
        for(int index=0;index<nums.Length;index++)
        {
            if(nums[index] > 0)
                result.Add(index+1);
        }
        return result;
    }
}

Time Complexity: O(n)

Space Complexity: O(1)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s