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]

Brainstorm

This is extremely similar to the previous problem 1.3 Find All Duplicates in an Array, except this time, instead of finding duplicates (occurrences >= 2), we're finding disappearances (occurrences = 0). So we can perhaps adopt the same approach we used in solving that problem here.

Approach #1: Use the Array Itself to Help Us Keep Track of Disappearances

We iterate through the array and on any element nums[i], we mark the element at nums[abs(nums[i]) - 1] as negative if it hasn't been already. We perform a second iteration to collect all numbers that are still positive, as these indicate that they haven't been encountered before, thereby marking a disappearance. Note that since we marked nums[nums[i] - 1] as negative, when adding back the actual elements, we convert their indices back as i + 1.

vector<int> findDisappearedNumbers(vector<int>& nums) {
    vector<int> missingNo;
    for (int i = 0; i < nums.size(); i++) {
        int val = abs(nums[i]) - 1;
        if (nums[val] > 0) 
            nums[val] = -nums[val];
    }
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i] > 0) 
            missingNo.push_back(i+1);
    }
    return missingNo;
}

Time complexity: $$O(n)$$

There are two iterations of the array, each of O(n) time complexity, adding up to O(2n) time complexity. Since we drop constants with Big O calculations, the overall complexity is O(n).

Space complexity: $$O(1)$$

results matching ""

    No results matching ""