Find the only missing number in a sorted array using C++

C++Server Side ProgrammingProgramming

In this problem, we are given an arr[] of size N containing values from 1 to N with one value missing in the array. Our task is to find the only missing number in a sorted array.

Let’s take an example to understand the problem,

Input

arr[] = {1, 2, 3, 5, 6, 7}

Output

4

Solution Approach

A simple solution to the problem is by traversing the sorted array linearly. And then check for the missing value using the fact that arr[i] = (i + 1).

Example 1

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findMissingValArray(int arr[], int N){
   for(int i = 0; i < N; i++){
      if(arr[i] != (i+1))
         return (i+1);
   }
   return -1;
}
int main(){
   int arr[] = {1, 2, 3, 4, 6};
   int N = sizeof(arr)/sizeof(arr[0]);
   cout<<"The missing value from the array is "<<findMissingValArray(arr, N);
   return 0;
}

Output

The missing value from the array is 5

Another approach to solve the problem is using binary search and checking the value at mid. If the value at mid is mid+1 and value at (mid - 1) is (mid) then we will traverse the left subarray and vise versa.

Example 2

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findMissingValArray(int arr[], int N){
   int s = 0, e = N - 1;
   while (s <= e) {
      int mid = (s + e) / 2;
      if (arr[mid] != mid + 1 && arr[mid - 1] == mid)
         return (mid + 1);
      if (arr[mid] != (mid + 1))
         e = (mid - 1);
      else
         s = (mid + 1);
   }
   return -1;
}
int main(){
   int arr[] = {1, 2, 3, 4, 6};
   int N = sizeof(arr)/sizeof(arr[0]);
   cout<<"The missing value from the array is "<<findMissingValArray(arr, N);
   return 0;
}

Output

The missing value from the array is 5
raja
Updated on 11-Feb-2022 11:45:42

Advertisements