Find the one missing number in range using C++

C++Server Side ProgrammingProgramming

In this problem, we are given an arr[] of size n. Our task is to find the one missing number in range.

The array consists of all values ranging from smallest value to (smallest + n). One element of the range is missing from the array. And we need to find this missing value.

Let’s take an example to understand the problem,

Input

arr[] = {4, 8, 5, 7}

Output

6

Solution Approach

A simple solution to the problem is by searching the missing element by sorting the array and then finding the first element of range starting from minimum value which is not present in the array but present in the range.

This solution is a naive approach and will solve the problem is O(n log n) time complexity.

Another approach to solving the problem in less time is using XOR of the values of the array and the range. We will find the XOR of all values in the range and also find the XOR of all values of the array. The XOR of both these values will be our missing value.

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
int findMissingNumArr(int arr[], int n){
   int arrMin = *min_element(arr, arr+n);
   int numXor = 0;
   int rangeXor = arrMin;
   for (int i = 0; i < n; i++) {
      numXor ^= arr[i];
      arrMin++;
      rangeXor ^= arrMin;
   }
   return numXor ^ rangeXor;
}
int main(){
   int arr[] = { 5, 7, 4, 8, 9};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"The missing value in the array is "<<findMissingNumArr(arr, n);
   return 0;
}

Output

The missing value in the array is 6
raja
Updated on 11-Feb-2022 11:31:24

Advertisements