Open In App

Find the only missing number in a sorted array

Last Updated : 09 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

You are given a sorted array of N integers from 1 to N with one number missing find the missing number

Examples: 
 

Input :ar[] = {1, 3, 4, 5}
Output : 2

Input : ar[] = {1, 2, 3, 4, 5, 7, 8}
Output : 6


 


A simple solution is to linearly traverse the given array. Find the point where current element is not one more than previous.
An efficient solution is to use binary search. We use the index to search for the missing element and modified binary search. If element at mid != index+1 and this is first missing element then mid + 1 is the missing element. Else if this is not first missing element but ar[mid] != mid+1 search in left half. Else search in right half and if left>right then no element is missing. 
 

C++
// CPP program to find the only missing element.
#include <iostream>
using namespace std;

int findmissing(int ar[], int N)
{
    int l = 0, r = N - 1;
    while (l <= r) {

        int mid = (l + r) / 2;

        // If this is the first element 
        // which is not index + 1, then 
        // missing element is mid+1
        if (ar[mid] != mid + 1 && 
                        ar[mid - 1] == mid)
            return mid + 1;

        // if this is not the first missing 
        // element search in left side
        if (ar[mid] != mid + 1)
            r = mid - 1;

        // if it follows index+1 property then 
        // search in right side
        else
            l = mid + 1;
    }

    // if no element is missing
    return -1;
}

// Driver code
int main()
{
    int arr[] = {1, 2, 3, 4, 5, 7, 8};
    int N = sizeof(arr)/sizeof(arr[0]);
    cout << findmissing(arr, N);
    return 0;
}
Java
// Java program to find 
// the only missing element.
class GFG
{
static int findmissing(int [] ar, int N)
{
    
    int l = 0, r = N - 1;
    while (l <= r) 
    {
        int mid = (l + r) / 2;
    
        // If this is the first element 
        // which is not index + 1, then 
        // missing element is mid+1
        if (ar[mid] != mid + 1 && 
            ar[mid - 1] == mid)
            return (mid + 1);
    
        // if this is not the first
        // missing element search
        // in left side
        if (ar[mid] != mid + 1)
            r = mid - 1;
    
        // if it follows index+1
        // property then search
        // in right side
        else
            l = mid + 1;
    }

// if no element is missing
return -1;
}

// Driver code
public static void main(String [] args)
{
    int arr[] = {1, 2, 3, 4, 5, 7, 8};
    int N = arr.length;
    System.out.println(findmissing(arr, N));
}
}

// This code is contributed 
// by Shivi_Aggarwal
Python
# PYTHON 3 program to find 
# the only missing element.
def findmissing(ar, N):
    l = 0
    r = N - 1
    while (l <= r): 
        mid = (l + r) / 2
        mid= int (mid)

    # If this is the first element 
    # which is not index + 1, then 
    # missing element is mid+1
        if(ar[mid] != mid + 1 and
           ar[mid - 1] == mid):
            return (mid + 1)

    # if this is not the first 
    # missing element search 
    # in left side
        elif(ar[mid] != mid + 1):
            r = mid - 1

    # if it follows index+1 
    # property then search 
    # in right side
        else:
            l = mid + 1
    
    # if no element is missing
    return (-1)
    
def main():
    ar= [1, 2, 3, 4, 5, 7, 8]
    N = len(ar)
    res= findmissing(ar, N)
    print (res)
if __name__ == "__main__":
    main()

# This code is contributed 
# by Shivi_Aggarwal
C#
// C# program to find 
// the only missing element.
using System;

class GFG
{
static int findmissing(int []ar, 
                       int N)
{
    
    int l = 0, r = N - 1;
    while (l <= r) 
    {
        int mid = (l + r) / 2;
    
        // If this is the first element 
        // which is not index + 1, then 
        // missing element is mid+1
        if (ar[mid] != mid + 1 && 
            ar[mid - 1] == mid)
            return (mid + 1);
    
        // if this is not the first
        // missing element search
        // in left side
        if (ar[mid] != mid + 1)
            r = mid - 1;
    
        // if it follows index+1
        // property then search
        // in right side
        else
            l = mid + 1;
    }

// if no element is missing
return -1;
}

// Driver code
public static void Main()
{
    int []arr = {1, 2, 3, 4, 5, 7, 8};
    int N = arr.Length;
    Console.WriteLine(findmissing(arr, N));
}
}

// This code is contributed 
// by Akanksha Rai(Abby_akku)
Javascript
<script>

// JavaScript program to find the only missing element.

      function findmissing(ar, N) {
        var l = 0,
          r = N - 1;
        while (l <= r) {
          var mid = parseInt((l + r) / 2);

          // If this is the first element
          // which is not index + 1, then
          // missing element is mid+1
          if (ar[mid] != mid + 1 && ar[mid - 1] == mid) 
          return mid + 1;

          // if this is not the first missing
          // element search in left side
          if (ar[mid] != mid + 1) r = mid - 1;
          // if it follows index+1 property then
          // search in right side
          else l = mid + 1;
        }

        // if no element is missing
        return -1;
      }

      // Driver code
      var arr = [1, 2, 3, 4, 5, 7, 8];
      var N = arr.length;
      document.write(findmissing(arr, N));
      
</script>
PHP
<?php
// PHP program to find 
// the only missing element. 
function findmissing(&$ar, $N)
{
    $r = $N - 1;
    $l = 0;
    while ($l <= $r)
    {
        $mid = ($l + $r) / 2;

        // If this is the first element 
        // which is not index + 1, then 
        // missing element is mid+1
        if ($ar[$mid] != $mid + 1 && 
            $ar[$mid - 1] == $mid)
            return ($mid + 1);

        // if this is not the first 
        // missing element search 
        // in left side
        if ($ar[$mid] != $mid + 1)
            $r = $mid - 1;

        // if it follows index+1 
        // property then search 
        // in right side
        else
            $l = $mid + 1;
    }

    // if no element is missing
    return (-1);
}

// Driver Code
$ar = array(1, 2, 3, 4, 5, 7, 8);
$N = sizeof($ar);
echo(findmissing($ar, $N));

// This code is contributed 
// by Shivi_Aggarwal
?> 

Output
6

Time Complexity:O(Log n) 
Auxiliary Space: O(1)

Find the only missing number in a sorted array Using Direct Formula approach

In this approach we will create Function to find the missing number using the sum of natural numbers formula. First we will Calculate the total sum of the first N natural numbers using formula n * (n + 1) / 2. Now we calculate sum of all elements in given array. Subtract the total sum with sum of all elements in given array and return the missing number.

Below is the implementation of above approach:

C++
#include <iostream>
#include <vector>

using namespace std;

int findMissingNumber(const vector<int>& nums)
{
    // Calculate the total sum
    int n = nums.size() + 1;
    int totalSum = n * (n + 1) / 2;

    // Calculate sum of all elements in the given array
    int arraySum = 0;
    for (int num : nums) {
        arraySum += num;
    }

    // Subtract  and return the total sum with the sum of
    // all elements in the array
    int missingNumber = totalSum - arraySum;

    return missingNumber;
}

int main()
{

    vector<int> numbers = { 1, 2, 3, 4, 5, 7, 8 };
    int missing = findMissingNumber(numbers);
    cout << "The only missing number is: " << missing
         << endl;

    return 0;
}
Python
def find_missing_number(nums):
    # Calculate the total sum
    n = len(nums) + 1
    total_sum = n * (n + 1) // 2

    # Calculate sum of all elements in the given array
    array_sum = sum(nums)

    # Subtract and return the total sum with the sum of
    # all elements in the array
    missing_number = total_sum - array_sum

    return missing_number


if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5, 7, 8]
    missing = find_missing_number(numbers)
    print("The only missing number is:", missing)
# This code is contributed by Ayush Mishra

Output
The only missing number is: 6

Time Complexity:O(1) 

Auxiliary Space: O(1)
 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads