Find the smallest missing number

09 Jun, 2022
Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array. 
Examples 
Input: {0, 1, 2, 6, 9}, n = 5, m = 10 
Output: 3

Input: {4, 5, 10, 11}, n = 4, m = 12 
Output: 0

Input: {0, 1, 2, 3}, n = 4, m = 5 
Output: 4

Input: {0, 1, 2, 3, 4, 5, 6, 7, 10}, n = 9, m = 11 
Output: 8
Thanks to Ravichandra for suggesting following two methods.
Method 1 (Use Binary Search) For i = 0 to m-1, do binary search for i in the array. If i is not present in the array then return i.Time Complexity: O(m log n) 
Method 2 (Linear Search) If arr[0] is not 0, return 0. Otherwise traverse the input array starting from index 0, and for each pair of elements a[i] and a[i+1], find the difference between them. if the difference is greater than 1 then a[i]+1 is the missing number. Time Complexity: O(n)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Method 3 (Use Modified Binary Search) Thanks to yasein and Jams for suggesting this method. In the standard Binary Search process, the element to be searched is compared with the middle element and on the basis of comparison result, we decide whether to search is over or to go to left half or right half. In this method, we modify the standard Binary Search algorithm to compare the middle element with its index and make decision on the basis of this comparison.
If the first element is not same as its index then return first index
Else get the middle index say midIf arr[mid] greater than mid then the required element lies in left half.Else the required element lies in right half.
If arr[mid] greater than mid then the required element lies in left half.
Else the required element lies in right half.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find the smallest elements// missing in a sorted array.#include<bits/stdc++.h>using namespace std; int findFirstMissing(int array[],                    int start, int end){    if (start > end)        return end + 1;     if (start != array[start])        return start;     int mid = (start + end) / 2;     // Left half has all elements    // from 0 to mid    if (array[mid] == mid)        return findFirstMissing(array,                            mid+1, end);     return findFirstMissing(array, start, mid);} // Driver codeint main(){    int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10};    int n = sizeof(arr)/sizeof(arr[0]);    cout << "Smallest missing element is " <<        findFirstMissing(arr, 0, n-1) << endl;} // This code is contributed by// Shivi_Aggarwal
// C program to find the smallest elements missing// in a sorted array.#include<stdio.h> int findFirstMissing(int array[], int start, int end){    if (start  > end)        return end + 1;     if (start != array[start])        return start;     int mid = (start + end) / 2;     // Left half has all elements from 0 to mid    if (array[mid] == mid)        return findFirstMissing(array, mid+1, end);     return findFirstMissing(array, start, mid);} // driver program to test above functionint main(){    int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10};    int n = sizeof(arr)/sizeof(arr[0]);    printf("Smallest missing element is %d",           findFirstMissing(arr, 0, n-1));    return 0;}
class SmallestMissing{    int findFirstMissing(int array[], int start, int end)    {        if (start > end)            return end + 1;         if (start != array[start])            return start;         int mid = (start + end) / 2;         // Left half has all elements from 0 to mid        if (array[mid] == mid)            return findFirstMissing(array, mid+1, end);         return findFirstMissing(array, start, mid);    }     // Driver program to test the above function    public static void main(String[] args)    {        SmallestMissing small = new SmallestMissing();        int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10};        int n = arr.length;        System.out.println("First Missing element is : "                + small.findFirstMissing(arr, 0, n - 1));    }}
# Python3 program to find the smallest# elements missing in a sorted array. def findFirstMissing(array, start, end):     if (start > end):        return end + 1     if (start != array[start]):        return start;     mid = int((start + end) / 2)     # Left half has all elements    # from 0 to mid    if (array[mid] == mid):        return findFirstMissing(array,                          mid+1, end)     return findFirstMissing(array,                          start, mid)  # driver program to test above functionarr = [0, 1, 2, 3, 4, 5, 6, 7, 10]n = len(arr)print("Smallest missing element is",      findFirstMissing(arr, 0, n-1)) # This code is contributed by Smitha Dinesh Semwal
// C# program to find the smallest// elements missing in a sorted array.using System; class GFG{    static int findFirstMissing(int []array,                            int start, int end)    {        if (start > end)            return end + 1;         if (start != array[start])            return start;         int mid = (start + end) / 2;         // Left half has all elements from 0 to mid        if (array[mid] == mid)            return findFirstMissing(array, mid+1, end);         return findFirstMissing(array, start, mid);    }     // Driver program to test the above function    public static void Main()    {        int []arr = {0, 1, 2, 3, 4, 5, 6, 7, 10};        int n = arr.Length;                 Console.Write("smallest Missing element is : "                    + findFirstMissing(arr, 0, n - 1));    }} // This code is contributed by Sam007
<?php// PHP program to find the// smallest elements missing// in a sorted array. // function that returns// smallest elements missing// in a sorted array.function findFirstMissing($array, $start, $end){    if ($start > $end)        return $end + 1;     if ($start != $array[$start])        return $start;     $mid = ($start + $end) / 2;     // Left half has all    // elements from 0 to mid    if ($array[$mid] == $mid)        return findFirstMissing($array,                                $mid + 1,                                $end);     return findFirstMissing($array,                            $start,                            $mid);}     // Driver Code    $arr = array (0, 1, 2, 3, 4, 5, 6, 7, 10);    $n = count($arr);    echo "Smallest missing element is " ,          findFirstMissing($arr, 2, $n - 1);         // This code Contributed by Ajit.?>
<script>     // Javascript program to find the smallest    // elements missing in a sorted array.         function findFirstMissing(array, start, end)    {        if (start > end)            return end + 1;           if (start != array[start])            return start;           let mid = parseInt((start + end) / 2, 10);           // Left half has all elements from 0 to mid        if (array[mid] == mid)            return findFirstMissing(array, mid+1, end);           return findFirstMissing(array, start, mid);    }         let arr = [0, 1, 2, 3, 4, 5, 6, 7, 10];    let n = arr.length;     document.write("smallest Missing element is " +    findFirstMissing(arr, 0, n - 1));     </script>
Smallest missing element is 8
Note: This method doesn’t work if there are duplicate elements in the array.Time Complexity: O(Log n)
Auxiliary Space : O(Log n)
Another Method: The idea is to use Recursive Binary Search to find the smallest missing number. Below is the illustration with the help of steps:
If the first element of the array is not 0, then the smallest missing number is 0.
If the last elements of the array is N-1, then the smallest missing number is N.
Otherwise, find the middle element from the first and last index and check if the middle element is equal to the desired element. i.e. first + middle_index.If the middle element is the desired element, then the smallest missing element is in the right search space of the middle.Otherwise, the smallest missing number is in the left search space of the middle.
If the middle element is the desired element, then the smallest missing element is in the right search space of the middle.
Otherwise, the smallest missing number is in the left search space of the middle.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
//C++ program for the above approach#include <bits/stdc++.h> using namespace std; // Program to find missing elementint findFirstMissing(vector<int> arr , int start ,                        int  end,int first){   if (start < end)  {    int mid = (start + end) / 2;     /** Index matches with value      at that index, means missing      element cannot be upto that po*/    if (arr[mid] != mid+first)      return findFirstMissing(arr, start,                                 mid , first);    else      return findFirstMissing(arr, mid + 1,                                 end , first);  }  return start + first; } // Program to find Smallest// Missing in Sorted Arrayint findSmallestMissinginSortedArray(vector<int> arr){     // Check if 0 is missing  // in the array  if(arr[0] != 0)    return 0;   // Check is all numbers 0 to n - 1  // are present in array  if(arr[arr.size() - 1] == arr.size() - 1)    return arr.size();   int first = arr[0];   return findFirstMissing(arr, 0, arr.size() - 1, first);}  // Driver program to test the above functionint main(){    vector<int> arr = {0, 1, 2, 3, 4, 5, 7};    int n = arr.size();     // Function Call    cout<<"First Missing element is : "<<findSmallestMissinginSortedArray(arr);} // This code is contributed by mohit kumar 29.
// Java Program for above approachimport java.io.*; class GFG{       // Program to find Smallest    // Missing in Sorted Array    int findSmallestMissinginSortedArray(                              int[] arr)    {      // Check if 0 is missing      // in the array      if(arr[0] != 0)        return 0;             // Check is all numbers 0 to n - 1      // are present in array      if(arr[arr.length-1] == arr.length - 1)        return arr.length;             int first = arr[0];       return findFirstMissing(arr,0,                       arr.length-1,first);    }         // Program to find missing element    int findFirstMissing(int[] arr , int start ,                              int end, int first)    {             if (start < end)      {        int mid = (start+end)/2;         /** Index matches with value          at that index, means missing          element cannot be upto that point */        if (arr[mid] != mid+first)          return findFirstMissing(arr, start,                                     mid , first);        else          return findFirstMissing(arr, mid+1,                                     end , first);      }      return start+first;     }       // Driver program to test the above function    public static void main(String[] args)    {        GFG small = new GFG();        int arr[] = {0, 1, 2, 3, 4, 5, 7};        int n = arr.length;                 // Function Call        System.out.println("First Missing element is : "            + small.findSmallestMissinginSortedArray(arr));    }}
# Python3 program for above approach # Function to find Smallest # Missing in Sorted Arraydef findSmallestMissinginSortedArray(arr):         # Check if 0 is missing     # in the array    if (arr[0] != 0):        return 0         # Check is all numbers 0 to n - 1     # are present in array    if (arr[-1] == len(arr) - 1):        return len(arr)         first = arr[0]         return findFirstMissing(arr, 0,            len(arr) - 1, first) # Function to find missing element def findFirstMissing(arr, start, end, first):         if (start < end):        mid = int((start + end) / 2)                 # Index matches with value         # at that index, means missing        # element cannot be upto that point        if (arr[mid] != mid + first):            return findFirstMissing(arr, start,                                    mid, first)        else:            return findFirstMissing(arr, mid + 1,                                     end, first)         return start + first # Driver codearr = [ 0, 1, 2, 3, 4, 5, 7 ]n = len(arr) # Function Callprint("First Missing element is :",      findSmallestMissinginSortedArray(arr)) # This code is contributed by rag2127
// C# program for above approachusing System; class GFG{     // Program to find Smallest // Missing in Sorted Arrayint findSmallestMissinginSortedArray(int[] arr) {          // Check if 0 is missing     // in the array    if (arr[0] != 0)        return 0;         // Check is all numbers 0 to n - 1     // are present in array    if (arr[arr.Length - 1] == arr.Length - 1)        return arr.Length;         int first = arr[0];         return findFirstMissing(arr, 0,           arr.Length - 1,first);}     // Program to find missing element int findFirstMissing(int[] arr , int start ,                      int end, int first) {         if (start < end)     {        int mid = (start + end) / 2;                 /*Index matches with value         at that index, means missing        element cannot be upto that point */        if (arr[mid] != mid+first)            return findFirstMissing(arr, start,                                     mid, first);        else            return findFirstMissing(arr, mid + 1,                                     end, first);    }    return start + first;} // Driver codestatic public void Main (){    GFG small = new GFG();    int[] arr = {0, 1, 2, 3, 4, 5, 7};    int n = arr.Length;         // Function Call    Console.WriteLine("First Missing element is : " +    small.findSmallestMissinginSortedArray(arr));}} // This code is contributed by avanitrachhadiya2155
<script> // Javascript program for the above approach // Program to find missing elementfunction findFirstMissing(arr, start, end, first){    if (start < end)    {        let mid = (start + end) / 2;             /** Index matches with value        at that index, means missing        element cannot be upto that po*/        if (arr[mid] != mid + first)            return findFirstMissing(arr, start,                                    mid, first);        else            return findFirstMissing(arr, mid + 1,                                    end, first);    }    return start + first;} // Program to find Smallest// Missing in Sorted Arrayfunction findSmallestMissinginSortedArray(arr){         // Check if 0 is missing    // in the array    if (arr[0] != 0)        return 0;         // Check is all numbers 0 to n - 1    // are present in array    if (arr[arr.length - 1] == arr.length - 1)        return arr.length;         let first = arr[0];         return findFirstMissing(        arr, 0, arr.length - 1, first);} // Driver codelet arr = [ 0, 1, 2, 3, 4, 5, 7 ];let n = arr.length; // Function Calldocument.write("First Missing element is : " +     findSmallestMissinginSortedArray(arr)); // This code is contributed by Mayank Tyagi </script>
First Missing element is : 6
Time Complexity: O(Log n) 
Auxiliary Space : O(Log n)
Find the smallest missing number | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFind the smallest missing number | GeeksforGeeksWatch laterShareCopy link81/101InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:26•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=s60sUkWh7TI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.
jit_t
Shivi_Aggarwal
amitbhatia.ab
ukasp
avanitrachhadiya2155
rag2127
rameshtravel07
mohit kumar 29
mayanktyagi1709
rajeev0719singh
_shinchancode
Binary Search
Arrays
Arrays
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
Subset Sum Problem | DP-25
Introduction to Data Structures
Python | Using 2D arrays/lists the right way