# Find All Numbers Disappeared in an Array in C++

Suppose we have an array of n elements. Some elements appear twice and other appear once. Elements are in range 1 <= A[i] <= n. We have to find those elements that are not present in the array. The constraint is that we have to solve this problem without using extra space, and time will be O(n).

So if the array is [4, 3, 2, 7, 8, 2, 3, 1], then result will be [5, 6]

To solve this, we will follow these steps −

• let n is the size of the array
• for i in range 0 to n – 1
• x := |A[i]| - 1
• if A[x] > 0, then A[x] := - A[x]
• define answer as an array
• for i in range 0 to n – 1
• if A[i] > 0, then add i + 1 into the answer
• return the answer

## Example

Let us see the following implementation to get better understanding −

class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& v) {
int n = v.size();
for(int i = 0;i < n; i++){
int x = abs(v[i]) - 1;
if(v[x] > 0) v[x] = -v[x];
}
vector <int> ans;
for(int i = 0; i < n; i++){
if(v[i]>0)ans.push_back(i+1);
}
return ans;
}
};

## Input

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

## Output

[5,6]
Published on 16-Jan-2020 10:47:39
Advertisements