Find the Missing Number

05 Jul, 2022
You are given a list of n-1 integers and these integers are in the range of 1 to n. There are no duplicates in the list. One of the integers is missing from the list. Write an efficient code to find the missing integer.Example: 
Input: arr[] = {1, 2, 4, 6, 3, 7, 8}Output: 5Explanation: The missing number between 1 to 8 is 5
Input: arr[] = {1, 2, 3, 5}Output: 4Explanation: The missing number between 1 to 5 is 4
Method 1: This method uses the technique of the Summation formula. 
Approach: The length of the array is n-1. So, the sum of all n elements i.e. sum of numbers from 1 to n can be calculated using the formula n*(n+1)/2. Now find the sum of all the elements in the array and subtract it from the sum of the first n natural numbers, it will give us the value of the missing element.
Algorithm: Calculate the sum of the first n natural numbers as sumtotal= n*(n+1)/2Create a variable sum to store the sum of the array elements.Traverse the array from start to end.Update the value of sum as sum = sum + array[i]Print the missing number as SumTotal – sum
Calculate the sum of the first n natural numbers as sumtotal= n*(n+1)/2Create a variable sum to store the sum of the array elements.Traverse the array from start to end.Update the value of sum as sum = sum + array[i]Print the missing number as SumTotal – sum
Calculate the sum of the first n natural numbers as sumtotal= n*(n+1)/2
Create a variable sum to store the sum of the array elements.
Traverse the array from start to end.
Update the value of sum as sum = sum + array[i]
Print the missing number as SumTotal – sum
Below is the implementation of the above approach:
C++14
C
Java
Python
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; // Function to get the missing numberint getMissingNo(int a[], int n){     int total = (n + 1) * (n + 2) / 2;    for (int i = 0; i < n; i++)        total -= a[i];    return total;} // Driver Codeint main(){    int arr[] = { 1, 2, 4, 5, 6 };    int n = sizeof(arr) / sizeof(arr[0]);    int miss = getMissingNo(arr, n);    cout << miss;}
#include <stdio.h> /* getMissingNo takes array and size of array as arguments*/int getMissingNo(int a[], int n){    int i, total;    total = (n + 1) * (n + 2) / 2;    for (i = 0; i < n; i++)        total -= a[i];    return total;} /*program to test above function */int main(){    int a[] = { 1, 2, 4, 5, 6 };    int miss = getMissingNo(a, 5);    printf("%d", miss);    getchar();}
// Java program to find missing Numberimport java.util.*;import java.util.Arrays;class GFG {    public static int    findDisappearedNumbers(int[] nums)    {        int n=nums.length;        int sum=((n+1)*(n+2))/2;        for(int i=0;i<n;i++)          sum-=nums[i];        return sum;    }    public static void main(String[] args)    {        int[] a = { 1, 2, 4, 5, 6 };        System.out.println(findDisappearedNumbers(a));    }}
# getMissingNo takes list as argumentdef getMissingNo(A):    n = len(A)    total = (n + 1)*(n + 2)/2    sum_of_A = sum(A)    return total - sum_of_A  # Driver program to test the above functionA = [1, 2, 4, 5, 6]miss = getMissingNo(A)print(miss)# This code is contributed by Pratik Chhajer
// C# program to find missing Numberusing System; class GFG {    // Function to ind missing number    static int getMissingNo(int[] a, int n)    {        int total = (n + 1) * (n + 2) / 2;         for (int i = 0; i < n; i++)            total -= a[i];         return total;    }     /* program to test above function */    public static void Main()    {        int[] a = { 1, 2, 4, 5, 6 };        int miss = getMissingNo(a, 5);        Console.Write(miss);    }} // This code is contributed by Sam007_
<?php// PHP program to find// the Missing Number // getMissingNo takes array and// size of array as argumentsfunction getMissingNo ($a, $n){    $total = ($n + 1) * ($n + 2) / 2;    for ( $i = 0; $i < $n; $i++)        $total -= $a[$i];    return $total;} // Driver Code$a = array(1, 2, 4, 5, 6);$miss = getMissingNo($a, 5);echo($miss); // This code is contributed by Ajit.?>
<script>      // Function to get the missing number    function getMissingNo(a, n) {          let total = Math.floor((n + 1) * (n + 2) / 2);        for (let i = 0; i < n; i++)            total -= a[i];        return total;    }      // Driver Code     let arr = [ 1, 2, 4, 5, 6 ];    let n = arr.length;    let miss = getMissingNo(arr, n);    document.write(miss); // This code is contributed by Surbhi Tyagi </script>
3
Complexity Analysis: 
Time Complexity: O(n). Only one traversal of the array is needed.
Space Complexity: O(1). No extra space is needed
Modification for Overflow :Approach: The approach remains the same but there can be an overflow if n is large. In order to avoid integer overflow, pick one number from the known numbers and subtract that one number from the given numbers. This way there won’t be any Integer Overflow.
Algorithm: 
Create a variable sum = 1 which will store the missing number and a counter variable c = 2.Traverse the array from start to end.Update the value of sum as sum = sum – array[i] + c and increment c as c++.Print the missing number as a sum.
Create a variable sum = 1 which will store the missing number and a counter variable c = 2.
Traverse the array from start to end.
Update the value of sum as sum = sum – array[i] + c and increment c as c++.
Print the missing number as a sum.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; int getMissingNo(int a[], int n){    int i, total = 1;     for (i = 2; i <= (n + 1); i++) {        total += i;        total -= a[i - 2];    }    return total;} // Driver Programint main(){    int arr[] = { 1, 2, 3, 5 };    cout << getMissingNo(arr, sizeof(arr) / sizeof(arr[0]));    return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
#include <stdio.h> int getMissingNo(int a[], int n){    int i, total = 1;     for (i = 2; i <= (n + 1); i++) {        total += i;        total -= a[i - 2];    }    return total;} // Driver Programint main(){    int arr[] = { 1, 2, 3, 5 };    printf("%d",getMissingNo(arr, sizeof(arr) / sizeof(arr[0])));    return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java implementationclass GFG {    static int getMissingNo(int a[], int n)    {        int total = 1;        for (int i = 2; i <= (n + 1); i++) {            total += i;            total -= a[i - 2];        }        return total;    }     // Driver Code    public static void main(String[] args)    {        int[] arr = { 1, 2, 3, 5 };        System.out.println(getMissingNo(arr, arr.length));    }} // This code is contributed by Aditya Kumar (adityakumar129)
# a represents the array# n : Number of elements in array adef getMissingNo(a, n):    i, total = 0, 1     for i in range(2, n + 2):        total += i        total -= a[i - 2]    return total # Driver Codearr = [1, 2, 3, 5]print(getMissingNo(arr, len(arr))) # This code is contributed by Mohit kumar
using System; class GFG{     // a represents the array// n : Number of elements in array astatic int getMissingNo(int[] a, int n){    int i, total = 1;         for ( i = 2; i <= (n + 1); i++)    {        total += i;        total -= a[i - 2];    }    return total;} // Driver Codepublic static void Main(){    int[] arr = {1, 2, 3, 5};    Console.Write(getMissingNo(arr, (arr.Length)));     // Console.Write(getMissingNo(arr, 4));}}// This code is contributed by SoumikMondal
<script> // a represents the array// n : Number of elements in array afunction getMissingNo(a){    let n = a.length;    let i, total=1;         for (i = 2; i<= (n+1); i++)    {        total += i;        total -= a[i-2];    }    return total;} //Driver Program    let arr = [1, 2, 3, 5];    document.write(getMissingNo(arr));  //This code is contributed by Mayank Tyagi </script>
4
Complexity Analysis: 
Time Complexity: O(n). Only one traversal of the array is needed.
Space Complexity: O(1). No extra space is needed
Thanks to Sahil Rally for suggesting this improvement.Method 2: This method uses the technique of XOR to solve the problem.  
Approach: XOR has certain properties 
Assume a1 ^ a2 ^ a3 ^ ...^ an = a and a1 ^ a2 ^ a3 ^ ...^ an-1 = b
Then a ^ b = an
Algorithm: 
Create two variables a = 0 and b = 0Run a loop from 1 to n with i as counter.For every index, update a as a = a ^ iNow traverse the array from start to end.For every index, update b as b = b ^ array[i].Print the missing number as a ^ b.
Create two variables a = 0 and b = 0
Run a loop from 1 to n with i as counter.
For every index, update a as a = a ^ i
Now traverse the array from start to end.
For every index, update b as b = b ^ array[i].
Print the missing number as a ^ b.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; // Function to get the missing numberint getMissingNo(int a[], int n){    // For xor of all the elements in array    int x1 = a[0];     // For xor of all the elements from 1 to n+1    int x2 = 1;     for (int i = 1; i < n; i++)        x1 = x1 ^ a[i];     for (int i = 2; i <= n + 1; i++)        x2 = x2 ^ i;     return (x1 ^ x2);} // Driver Codeint main(){    int arr[] = { 1, 2, 4, 5, 6 };    int n = sizeof(arr) / sizeof(arr[0]);    int miss = getMissingNo(arr, n);    cout << miss;}
#include <stdio.h> /* getMissingNo takes array and size of array as arguments*/int getMissingNo(int a[], int n){    int i;    int x1 = a[0]; /* For xor of all the elements in array */    int x2 = 1; /* For xor of all the elements from 1 to n+1 */     for (i = 1; i < n; i++)        x1 = x1 ^ a[i];     for (i = 2; i <= n + 1; i++)        x2 = x2 ^ i;     return (x1 ^ x2);} /*program to test above function */int main(){    int a[] = { 1, 2, 4, 5, 6 };    int miss = getMissingNo(a, 5);    printf("%d", miss);    getchar();}
// Java program to find missing Number// using xorclass Main {    // Function to find missing number    static int getMissingNo(int a[], int n)    {        int x1 = a[0];        int x2 = 1;         /* For xor of all the elements           in array */        for (int i = 1; i < n; i++)            x1 = x1 ^ a[i];         /* For xor of all the elements           from 1 to n+1 */        for (int i = 2; i <= n + 1; i++)            x2 = x2 ^ i;         return (x1 ^ x2);    }     /* program to test above function */    public static void main(String args[])    {        int a[] = { 1, 2, 4, 5, 6 };        int miss = getMissingNo(a, 5);        System.out.println(miss);    }}
# Python3 program to find# the missing Number# getMissingNo takes list as argument def getMissingNo(a, n):    x1 = a[0]    x2 = 1         for i in range(1, n):        x1 = x1 ^ a[i]             for i in range(2, n + 2):        x2 = x2 ^ i         return x1 ^ x2  # Driver program to test above functionif __name__=='__main__':     a = [1, 2, 4, 5, 6]    n = len(a)    miss = getMissingNo(a, n)    print(miss)     # This code is contributed by Yatin Gupta
// C# program to find missing Number// using xorusing System; class GFG {    // Function to find missing number    static int getMissingNo(int[] a, int n)    {        int x1 = a[0];        int x2 = 1;         /* For xor of all the elements        in array */        for (int i = 1; i < n; i++)            x1 = x1 ^ a[i];         /* For xor of all the elements        from 1 to n+1 */        for (int i = 2; i <= n + 1; i++)            x2 = x2 ^ i;         return (x1 ^ x2);    }     /* driver program to test above function */    public static void Main()    {        int[] a = { 1, 2, 4, 5, 6 };        int miss = getMissingNo(a, 5);        Console.Write(miss);    }} // This code is contributed by Sam007_
<?php// PHP program to find// the Missing Number// getMissingNo takes array and// size of array as argumentsfunction getMissingNo($a, $n){    // For xor of all the    // elements in array    $x1 = $a[0];         // For xor of all the    // elements from 1 to n + 1    $x2 = 1;         for ($i = 1; $i < $n; $i++)        $x1 = $x1 ^ $a[$i];                 for ($i = 2; $i <= $n + 1; $i++)        $x2 = $x2 ^ $i;             return ($x1 ^ $x2);} // Driver Code$a = array(1, 2, 4, 5, 6);$miss = getMissingNo($a, 5);echo($miss); // This code is contributed by Ajit.?>
<script>      // Function to get the missing number      function getMissingNo(a, n)      {               // For xor of all the elements in array        var x1 = a[0];         // For xor of all the elements from 1 to n+1        var x2 = 1;        for (var i = 1; i < n; i++) x1 = x1 ^ a[i];        for (var i = 2; i <= n + 1; i++) x2 = x2 ^ i;         return x1 ^ x2;      }       // Driver Code       var arr = [1, 2, 4, 5, 6];      var n = arr.length;      var miss = getMissingNo(arr, n);      document.write(miss);             // This code is contributed by rdtank.    </script>
3
Complexity Analysis: 
Time Complexity: O(n). Only one traversal of the array is needed.
Space Complexity: O(1). No extra space is needed.
Method 3: This method will work only in python. Approach: Take the sum of all elements in the array and subtract that from the sum of n+1 elements. For Eg: If my elements are li=[1,2,4,5] then take the sum of all elements in li and subtract it from the sum of len(li)+1 elements. The following code shows the demonstration. 
C++
C
Java
Python3
C#
Javascript
// C++ program to find the missing Number#include <bits/stdc++.h>using namespace std; // getMissingNo takes list as argumentint getMissingNo(int a[], int n){    int n_elements_sum = n * (n + 1) / 2;    int sum = 0;     for (int i = 0; i < n - 1; i++)        sum += a[i];    return n_elements_sum - sum;} // Driver codeint main(){    int a[] = { 1, 2, 4, 5, 6 };    int n = sizeof(a) / sizeof(a[0]) + 1;    int miss = getMissingNo(a, n);    cout << (miss);    return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to find the missing Number#include <stdio.h> // getMissingNo takes list as argumentint getMissingNo(int a[], int n){    int n_elements_sum = n * (n + 1) / 2;    int sum = 0;     for (int i = 0; i < n - 1; i++)        sum += a[i];    return n_elements_sum - sum;} // Driver codeint main(){    int a[] = { 1, 2, 4, 5, 6 };    int n = sizeof(a) / sizeof(a[0]) + 1;    int miss = getMissingNo(a, n);    printf("%d",miss);    return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to find the missing Numberclass GFG {     // getMissingNo function for finding missing number    static int getMissingNo(int a[], int n)    {        int n_elements_sum = n * (n + 1) / 2;        int sum = 0;         for (int i = 0; i < n - 1; i++)            sum += a[i];         return n_elements_sum - sum;    }     // Driver code    public static void main(String[] args)    {        int a[] = { 1, 2, 4, 5, 6 };        int n = a.length + 1;        int miss = getMissingNo(a, n);         System.out.print(miss);    }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to find# the missing Number# getMissingNo takes list as argumentdef getMissingNo(a, n):    n_elements_sum=n*(n+1)//2    return n_elements_sum-sum(a)  # Driver program to test above functionif __name__=='__main__':     a = [1, 2, 4, 5, 6]    n = len(a)+1    miss = getMissingNo(a, n)    print(miss)
// C# program to implement// the above approachusing System;class GFG{   // Function to find missing// numberstatic int getMissingNo(int[] a,                        int n){  int n_elements_sum = (n * (n + 1) / 2);  int sum = 0;   for (int i = 0; i < n - 1; i++)    sum = sum + a[i];   return (n_elements_sum - sum);} // Driver codepublic static void Main(){  int[] a = {1, 2, 4, 5, 6};  int miss = getMissingNo(a, 5);  Console.Write(miss);}} // This code is contributed by Virusbuddah
<script> // JavaScript program to find// the missing Number // getMissingNo takes list// as argumentfunction getMissingNo(a,n){         let n_elements_sum =Math.floor (n * (n + 1) / 2 );    let sum = 0;   for(let i = 0; i < n - 1; i++)    sum += a[i];  return n_elements_sum-sum;} // Driver Code    let a = [1, 2, 4, 5, 6];    let n=a.length+1;    let miss=getMissingNo(a,n)    document.write(miss);     // This code contributed by Rajput-Ji </script>
3
Time Complexity: O(n)Auxiliary Space: O(1)
Method 4: Efficient Approach using (Cyclic Sort)Approach: All the given array numbers are sorted and in the range of 1 to n-1. If the range is 1 to N  then every array element will be at the location, index == value-1 i.e. means at the 0th index value will be 1 similarly at the 1st index position value will be 2 and so on till nth value.
Below is the implementation of the above approach:
Java
Python3
C#
Javascript
// java program to check missingNoimport java.util.*;public class MissingNumber {    public static void main(String[] args)    {        int[] arr = { 1, 2, 4, 5, 6 };        int n = arr.length;        int ans = getMissingNo(arr, n);        System.out.println(ans);    }     static int getMissingNo(int[] arr, int n)    {        int i = 0;        while (i < n) {            // as array is of 1 based indexing so the            // correct position or index number of each            // element is element-1 i.e. 1 will be at 0th            // index similarly 2 correct index will 1 so            // on...            int correctpos = arr[i] - 1;            if (arr[i] < n && arr[i] != arr[correctpos]) {                // if array element should be lesser than                // size and array element should not be at                // its correct position then only swap with                // its correct positioin or index value                swap(arr, i, correctpos);            }            else {                // if element is at its correct position                // just increment i and check for remaining                // array elements                i++;            }        }      // check for missing element by comparing elements with their index values        for (int index = 0; index < arr.length; index++) {            if (arr[index] != index + 1) {                return index + 1;            }        }        return arr.length;    }     static void swap(int[] arr, int i, int correctpos)    {      // swap elements with their correct indexes        int temp = arr[i];        arr[i] = arr[correctpos];        arr[correctpos] = temp;    }}// this code is contributed by devendra solunke
# Python3 program to check missingNodef getMissingNo(arr, n) :    i = 0;         while (i < n) :        # as array is of 1 based indexing so the        # correct position or index number of each        # element is element-1 i.e. 1 will be at 0th        # index similarly 2 correct index will 1 so        # on...        correctpos = arr[i] - 1;        if (arr[i] < n and arr[i] != arr[correctpos]) :            # if array element should be lesser than            # size and array element should not be at            # its correct position then only swap with            # its correct positioin or index value            arr[i],arr[correctpos] = arr[correctpos], arr[i]         else :            # if element is at its correct position            # just increment i and check for remaining            # array elements            i += 1;                 # check for missing element by comparing elements with their index values    for index in range(n) :        if (arr[index] != index + 1) :            return index + 1;                 return n; if __name__ == "__main__" :    arr = [ 1, 2, 4, 5, 6 ];    n = len(arr);    print(getMissingNo(arr, n));      # This Code is Contributed by AnkThon
// C# program to implement// the above approachusing System;class GFG {     // Function to find missing    // number    static int getMissingNo(int[] arr, int n)    {        int i = 0;        while (i < n) {            // as array is of 1 based indexing so the            // correct position or index number of each            // element is element-1 i.e. 1 will be at 0th            // index similarly 2 correct index will 1 so            // on...            int correctpos = arr[i] - 1;            if (arr[i] < n && arr[i] != arr[correctpos]) {                // if array element should be lesser than                // size and array element should not be at                // its correct position then only swap with                // its correct positioin or index value                swap(arr, i, correctpos);            }            else {                // if element is at its correct position                // just increment i and check for remaining                // array elements                i++;            }        }        // check for missing element by comparing elements        // with their index values        for (int index = 0; index < n; index++) {            if (arr[index] != index + 1) {                return index + 1;            }        }        return n;    }     static void swap(int[] arr, int i, int correctpos)    {        // swap elements with their correct indexes        int temp = arr[i];        arr[i] = arr[correctpos];        arr[correctpos] = temp;    }    // Driver code    public static void Main()    {        int[] arr = { 1, 2, 4, 5, 6 };        int n = arr.Length;        int ans = getMissingNo(arr, n);        Console.Write(ans);    }} // This code is contributed by devendra solunke
// javascript program to check missingNo<script>        var arr = [ 1, 2, 4, 5, 6 ];        var n = arr.length;        var ans = getMissingNo(arr, n);        console.log(ans);     function getMissingNo(arr, n)    {        var i = 0;        while (i < n) {            // as array is of 1 based indexing so the            // correct position or index number of each            // element is element-1 i.e. 1 will be at 0th            // index similarly 2 correct index will 1 so            // on...            var correctpos = arr[i] - 1;            if (arr[i] < n && arr[i] != arr[correctpos]) {                // if array element should be lesser than                // size and array element should not be at                // its correct position then only swap with                // its correct positioin or index value                swap(arr, i, correctpos);            }            else {                // if element is at its correct position                // just increment i and check for remaining                // array elements                i++;            }        }      // check for missing element by comparing elements with their index values        for (var index = 0; index < arr.length; index++) {            if (arr[index] != index + 1) {                return index + 1;            }        }        return n;    }     function swap(arr, i, correctpos)    {      // swap elements with their correct indexes        var temp = arr[i];        arr[i] = arr[correctpos];        arr[correctpos] = temp;    }</script>// this code is contributed by devendra solunke
3
Time Complexity: O(N) requires (n-1) comparisons, so -1 is constant hence we can eliminate it, and the remaining n is complexity for the Best Case.
If an array is not sorted it will be the worst case for an algorithm and it will take O(N2) complexity. let’s see how we can calculate worst-case complexity. 
1 + 2 + 3 + 4 . . . . . .  . . . .  (n-1) comparisons will required so the sum of all natural numbers can be calculated using n*(n+1)/2. Hence we can conclude that time complexity is N2 
Space Complexity: O( 1) 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Find the missing number | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFind the missing number | GeeksforGeeksWatch laterShareCopy link3/101InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:47•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=lBk6fVhuCyw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
jit_t
YatinGupta
SoumikMondal
Ankur Goel
mohit kumar 29
Vivekkumar Singh
andrew1234
avsadityavardhan
ukasp
sujitmeshram
virusbuddha
subhammahato348
surbhityagi15
mayanktyagi1709
Rajput-Ji
rdtank
nijpadariya
palakdwivedi1
mridtz
akshaysingh98088
pranjalkakkar2181
adityakumar129
devendrasalunke
lucidcoder121
ankthon
simmytarika5
rkbhola5
Accolite
Amazon
Bitwise-XOR
Cisco
limited-range-elements
Microsoft
Morgan Stanley
Ola Cabs
Payu
Qualcomm
Samsung
Visa
Arrays
Searching
Morgan Stanley
Accolite
Amazon
Microsoft
Samsung
Ola Cabs
Payu
Visa
Cisco
Qualcomm
Arrays
Searching
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
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search, insert and delete in an unsorted array