Find the only missing number in a sorted array
Last Updated :
12 May, 2024
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
?>
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;
}
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static int findMissingNumber(List<Integer> 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;
}
public static void main(String[] args)
{
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(7);
numbers.add(8);
int missing = findMissingNumber(numbers);
System.out.println("The only missing number is: "
+ missing);
}
}
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
JavaScript
function findMissingNumber(nums) {
// Calculate the total sum
const n = nums.length + 1;
const totalSum = (n * (n + 1)) / 2;
// Calculate sum of all elements in the given array
let arraySum = 0;
for (let num of nums) {
arraySum += num;
}
// Subtract and return the total sum with the sum of
// all elements in the array
const missingNumber = totalSum - arraySum;
return missingNumber;
}
function main() {
const numbers = [1, 2, 3, 4, 5, 7, 8];
const missing = findMissingNumber(numbers);
console.log("The only missing number is: " + missing);
}
main();
OutputThe only missing number is: 6
Time Complexity: O(1)
Auxiliary Space: O(1)
Similar Reads
Find the missing number in a sorted array of limited range Given a sorted array of size n, consisting of integers from 1 to n+1 with one missing. The task is to find the missing element.Examples: Input : arr[] = [1, 3, 4, 5, 6]Output : 2Input : arr[] = [1, 2, 3, 4, 5, 7, 8, 9, 10]Output : 6Input: arr[] = [1, 2, 3, 4]Output: 5Using Linear Search - O(n) time
11 min read
Count of Missing Numbers in a sorted array Given a sorted array arr[], the task is to calculate the number of missing numbers between the first and last element of the sorted array. Examples: Input: arr[] = { 1, 4, 5, 8 } Output: 4 Explanation: The missing integers in the array are {2, 3, 6, 7}. Therefore, the count is 4. Input: arr[] = {5,
9 min read
Find the one missing number in range Given an array of size n. It is also given that range of numbers is from smallestNumber to smallestNumber + n where smallestNumber is the smallest number in array. The array contains number in this range but one number is missing so the task is to find this missing number. Examples: Input: arr[] = {
9 min read
Kth Missing Positive Number in a Sorted Array Given a sorted array of distinct positive integers arr[] and integer k, the task is to find the kth positive number that is missing from arr[].Examples : Input: arr[] = [2, 3, 4, 7, 11], k = 5Output: 9Explanation: Missing are 1, 5, 6, 8, 9, 10, ... and 5th missing number is 9.Input: arr[] = [1, 2, 3
10 min read
Find all missing numbers from a given sorted array Given a sorted array arr[] of N integers, The task is to find the multiple missing elements in the array between the ranges [arr[0], arr[N-1]]. Examples: Input: arr[] = {6, 7, 10, 11, 13}Output: 8 9 12 Explanation: The elements of the array are present in the range of the maximum and minimum array e
13 min read