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

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 
using namespace std;
int findMissingValArray(int arr[], int N){
   for(int i = 0; i 

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 
using namespace std;
int findMissingValArray(int arr[], int N){
   int s = 0, e = N - 1;
   while (s 

Output

The missing value from the array is 5
Updated on: 2022-02-11T11:45:42+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements