Given a list of n-1 integers and these integers are in the range of 1 to n. There are no duplicates in list. One of the integers is missing in the list. Write an efficient code to find the missing integer.
Input : arr = [1, 2, 3, 4, 6, 7, 8] Output : 5 Input : arr = [1, 2, 3, 4, 5, 6, 8, 9] Output : 7
One Simple solution is to apply methods discussed for finding the missing element in an unsorted array. Time complexity of this solution is O(n).
An efficient solution is based on the divide and conquer algorithm that we have seen in binary search, the concept behind this solution is that the elements appearing before the missing element will have ar[i] – i = 1 and those appearing after the missing element will have ar[i] – i = 2.
This solution has a time complexity of O(log n)
$mid = (int)(($a + $b) / 2);
if (($ar[$a] – $a) != ($ar[$mid] –
$b = $mid;
else if (($ar[$b] – $b) != ($ar[$mid] –
$a = $mid;
return ($ar[$mid] + 1);
// Driver Code
$ar = array(1, 2, 3, 4, 5, 6, 8 );
$size = sizeof($ar);
echo “Missing number: “,
// This code is contributed by ajit.
Missing number: 7
- Find the only missing number in a sorted array
- Find the missing number in a sorted array of limited range
- Find missing element in a sorted array of consecutive numbers
- Find the smallest positive number missing from an unsorted array | Set 2
- k-th missing element in sorted array
- Given a sorted array and a number x, find the pair in array whose sum is closest to x
- Find the number of elements greater than k in a sorted array
- Find the Missing Number
- Find four missing numbers in an array containing elements from 1 to N
- Find the one missing number in range
- Find the smallest missing number
- Find the missing number in Arithmetic Progression
- Find the missing number in Geometric Progression
- Find the index of first 1 in a sorted array of 0's and 1's
- Find the index of first 1 in an infinite sorted array of 0s and 1s
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.