Find All Numbers Disappeared in an Array in C++

C++Server Side ProgrammingProgramming

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 −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<int> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]";
}
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;
   }
};
main(){
   Solution ob;
   vector<int> v{4,3,2,7,8,2,3,5};
   print_vector(ob.findDisappearedNumbers(v));
}

Input

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

Output

[1, 6, ]
raja
Published on 16-Jan-2020 15:17:39
Advertisements