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 in the list. Write an efficient code to find the missing integer.
Example:
Input: arr[] = {1, 2, 4, 6, 3, 7, 8}
Output: 5
Explanation: The missing number from 1 to 8 is 5
Input: arr[] = {1, 2, 3, 5}
Output: 4
Explanation: The missing number from 1 to 5 is 4
Method 1: This method uses the technique of 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 first n natural numbers, it will be the value of the missing element.
- Algorithm:
- Calculate the sum of first n natural numbers as sumtotal= n*(n+1)/2
- create a variable sum to store the sum of 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
- Implementation:
C++
#include <bits/stdc++.h>usingnamespacestd;// Function to get the missing numberintgetMissingNo(inta[],intn){inttotal = (n + 1) * (n + 2) / 2;for(inti = 0; i < n; i++)total -= a[i];returntotal;}// Driver Codeintmain(){intarr[] = { 1, 2, 4, 5, 6 };intn =sizeof(arr) /sizeof(arr[0]);intmiss = getMissingNo(arr, n);cout << miss;}chevron_rightfilter_noneC
#include <stdio.h>/* getMissingNo takes array and size of array as arguments*/intgetMissingNo(inta[],intn){inti, total;total = (n + 1) * (n + 2) / 2;for(i = 0; i < n; i++)total -= a[i];returntotal;}/*program to test above function */intmain(){inta[] = { 1, 2, 4, 5, 6 };intmiss = getMissingNo(a, 5);printf("%d", miss);getchar();}chevron_rightfilter_noneJava
// Java program to find missing NumberclassMain {// Function to ind missing numberstaticintgetMissingNo(inta[],intn){inti, total;total = (n +1) * (n +2) /2;for(i =0; i < n; i++)total -= a[i];returntotal;}/* program to test above function */publicstaticvoidmain(String args[]){inta[] = {1,2,4,5,6};intmiss = getMissingNo(a,5);System.out.println(miss);}}chevron_rightfilter_nonePython
# getMissingNo takes list as argumentdefgetMissingNo(A):n=len(A)total=(n+1)*(n+2)/2sum_of_A=sum(A)returntotal-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 Chhajerchevron_rightfilter_noneC#
// C# program to find missing NumberusingSystem;classGFG {// Function to ind missing numberstaticintgetMissingNo(int[] a,intn){inttotal = (n + 1) * (n + 2) / 2;for(inti = 0; i < n; i++)total -= a[i];returntotal;}/* program to test above function */publicstaticvoidMain(){int[] a = { 1, 2, 4, 5, 6 };intmiss = getMissingNo(a, 5);Console.Write(miss);}}// This code is contributed by Sam007_chevron_rightfilter_nonePHP
<?php// PHP program to find// the Missing Number// getMissingNo takes array and// size of array as argumentsfunctiongetMissingNo ($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.?>chevron_rightfilter_noneOutput :
3
- Compelxity Analysis:
- Time Complexity: O(n).
Only one traversal of array is needed. - Space Complexity: O(1).
No extra space is needed
- Time Complexity: O(n).
Modification for Overflow
- Approach: The approach remains the same but there can be overflow if n is large. In order to avoid integer overflow, pick one number from known numbers and subtract one number from given numbers. This way there won’t have Integer Overflow ever.
- Algorithm:
- create a variable sum = 1 to which will store the missing number and a counter c = 2.
- Traverse the array from start to end.
- Update the value of sum as sum = sum – array[i] + c and update c as c++.
- print the missing number as sum.
-
Implementation:
C++
#include <bits/stdc++.h>usingnamespacestd;// a represents the array// n : Number of elements in array aintgetMissingNo(inta[],intn){inti, total=1;for( i = 2; i<= (n+1); i++){total+=i;total -= a[i-2];}returntotal;}//Driver Programintmain() {intarr[] = {1, 2, 3, 5};cout<<getMissingNo(arr,sizeof(arr)/sizeof(arr[0]));return0;}//This code is contributed by Ankur Goelchevron_rightfilter_noneJava
// Java implementationclassGFG{// a represents the array// n : Number of elements in array astaticintgetMissingNo(inta[],intn){inttotal =1;for(inti =2; i <= (n +1); i++){total += i;total -= a[i -2];}returntotal;}// Driver Codepublicstaticvoidmain(String[] args){int[] arr = {1,2,3,5};System.out.println(getMissingNo(arr, arr.length));}}// This post is contributed// by Vivek Kumar Singhchevron_rightfilter_nonePython3
# a represents the array# n : Number of elements in array adefgetMissingNo(a, n):i, total=0,1foriinrange(2, n+2):total+=itotal-=a[i-2]returntotal# Driver Codearr=[1,2,3,5]print(getMissingNo(arr,len(arr)))# This code is contributed by Mohit kumarchevron_rightfilter_noneC#
usingSystem;classGFG{// a represents the array// n : Number of elements in array astaticintgetMissingNo(int[] a,intn){inti, total = 1;for( i = 2; i <= (n + 1); i++){total += i;total -= a[i - 2];}returntotal;}// Driver CodepublicstaticvoidMain(){int[] arr = {1, 2, 3, 5};Console.Write(getMissingNo(arr, (arr.Length)));// Console.Write(getMissingNo(arr, 4));}}// This code is contributed by SoumikMondalchevron_rightfilter_none - Compelxity Analysis:
- Time Complexity: O(n).
Only one traversal of array is needed. - Space Complexity:O(1).
No extra space is needed
- Time Complexity: O(n).
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
Using this property, the missing element can be found. Calculate XOR of all the natural number from 1 to n and store it as a. Now calculate XOR of all the elements of the array and store it as b. The missing number will be a ^ b.
^ is XOR operator. - Algorithm:
- 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.
- Implementation:
C++
#include <bits/stdc++.h>usingnamespacestd;// Function to get the missing numberintgetMissingNo(inta[],intn){// For xor of all the elements in arrayintx1 = a[0];// For xor of all the elements from 1 to n+1intx2 = 1;for(inti = 1; i < n; i++)x1 = x1 ^ a[i];for(inti = 2; i <= n + 1; i++)x2 = x2 ^ i;return(x1 ^ x2);}// Driver Codeintmain(){intarr[] = { 1, 2, 4, 5, 6 };intn =sizeof(arr) /sizeof(arr[0]);intmiss = getMissingNo(arr, n);cout << miss;}chevron_rightfilter_noneC
#include <stdio.h>/* getMissingNo takes array and size of array as arguments*/intgetMissingNo(inta[],intn){inti;intx1 = a[0];/* For xor of all the elements in array */intx2 = 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 */intmain(){inta[] = { 1, 2, 4, 5, 6 };intmiss = getMissingNo(a, 5);printf("%d", miss);getchar();}chevron_rightfilter_noneJava
// Java program to find missing Number// using xorclassMain {// Function to find missing numberstaticintgetMissingNo(inta[],intn){intx1 = a[0];intx2 =1;/* For xor of all the elementsin array */for(inti =1; i < n; i++)x1 = x1 ^ a[i];/* For xor of all the elementsfrom 1 to n+1 */for(inti =2; i <= n +1; i++)x2 = x2 ^ i;return(x1 ^ x2);}/* program to test above function */publicstaticvoidmain(String args[]){inta[] = {1,2,4,5,6};intmiss = getMissingNo(a,5);System.out.println(miss);}}chevron_rightfilter_nonePython3
# Python3 program to find# the mising Number# getMissingNo takes list as argumentdefgetMissingNo(a, n):x1=a[0]x2=1foriinrange(1, n):x1=x1 ^ a[i]foriinrange(2, n+2):x2=x2 ^ ireturnx1 ^ 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 Guptachevron_rightfilter_noneC#
// C# program to find missing Number// using xorusingSystem;classGFG {// Function to find missing numberstaticintgetMissingNo(int[] a,intn){intx1 = a[0];intx2 = 1;/* For xor of all the elementsin array */for(inti = 1; i < n; i++)x1 = x1 ^ a[i];/* For xor of all the elementsfrom 1 to n+1 */for(inti = 2; i <= n + 1; i++)x2 = x2 ^ i;return(x1 ^ x2);}/* driver program to test above function */publicstaticvoidMain(){int[] a = { 1, 2, 4, 5, 6 };intmiss = getMissingNo(a, 5);Console.Write(miss);}}// This code is contributed by Sam007_chevron_rightfilter_nonePHP
<?php// PHP program to find// the Misiing Number// getMissingNo takes array and// size of array as argumentsfunctiongetMissingNo($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.?>chevron_rightfilter_none
Output:3
- Complexity Analysis:
- Time Complexity: O(n).
Only one traversal of array is needed. - Space Complexity: O(1).
No extra space is needed.
- Time Complexity: O(n).
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Find the one missing number in range
- Find the smallest missing number
- Find the missing number in Arithmetic Progression
- Find the Missing Number in a sorted array
- Find the missing number in Geometric Progression
- Find the only missing number in a sorted array
- Find missing number in another array which is shuffled copy
- Find the missing number in unordered Arithmetic Progression
- Find the smallest positive number missing from an unsorted array | Set 2
- Find the smallest positive number missing from an unsorted array | Set 3
- Find the smallest positive number missing from an unsorted array | Set 1
- Find the missing number in a sorted array of limited range
- Find the smallest positive number missing from an unsorted array : Hashing Implementation
- Find missing elements from an Array
- Find missing elements of a range
- Find n-variables from n sum equations with one missing
- Find the missing elements from 1 to M in given N ranges | Set-2
- Find the missing integer in an array if mean is given
- Find Two Missing Numbers | Set 2 (XOR based solution)
- Find four missing numbers in an array containing elements from 1 to N

