Write a program in C++ to find the missing positive number in a given array of unsorted integers


Let’s suppose we have given an array of unsorted integers. The task is to find the positive missing number which is not present in the given array in the range [0 to n]. For example,

Input-1

N = 9 arr = [0,2,5,9,1,7,4,3,6]

Output

8

Explanation − In the given unsorted array, ‘8’ is the only positive integer that is missing, thus the output is ‘8’.

Input-2 

>N= 1 arr= [0]

Output

1

Explanation − In the given array, ‘1’ is the only positive integer that is missing, thus the output is ‘1’.

Approach to solve this problem

There are several approaches to solve this particular problem. However, we can solve this problem in linear time O(n) and constant space O(1).

Since we know that our array is of size n and it contains exactly elements in the range of [0 to n]. So if we do XOR operation of each of the elements and its index with ‘n’, then we can find the resultant number as a unique number that is missing from the array.

  • Take Input of N size of the array with elements in the range [0 to n].

  • An integer function findMissingNumber(int arr[], int size) takes an array and its size as input and returns the missing number.

  • Let’s take n as a missing number to perform XOR operation.

  • Iterate over all the array elements and perform XOR operation with each of the array elements and its indexes with respect to missing number, i.e., n.

  • Now return the missing number.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
int findMissingNumber(int *arr, int size){
   int missing_no= size;
   for(int i=0;i<size;i++){
      missing_no^= i^arr[i];
   }
   return missing_no;
}
int main(){
   int n= 6;
   int arr[n]= {0,4,2,1,6,3};
   cout<<findMissingNumber(arr,n)<<endl;
   return 0;
}

Output

If we will run the above code then it will print the output as,

5

If we perform the XOR operation with each of the elements of the array and its indexes, it will print ‘5’ which is missing from the array.

Updated on: 05-Feb-2021

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements