Find the Missing Number in a sorted array
Last Updated :
03 May, 2024
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.
Examples:
Input : arr[] = [1, 2, 3, 4, 6, 7, 8]
Output : 5
Input : arr[] = [1, 2, 3, 4, 5, 6, 8, 9]
Output : 7
Naive approach: One Simple solution is to apply methods discussed for finding the missing element in an unsorted array.
Algorithm
- Create an empty hash table.
- Traverse through the given list of n-1 integers and insert each integer into the hash table.
- Traverse through the range of 1 to n and check whether each integer is present in the hash table or not.
- If any integer is not present in the hash table, then it is the missing integer.
Implementation
C++
#include <iostream>
#include <unordered_set>
using namespace std;
int findMissingNumber(int arr[], int n) {
unordered_set<int> hashSet;
// Add all elements of array to hashset
for (int i = 0; i < n-1; i++) {
hashSet.insert(arr[i]);
}
// Check each integer from 1 to n
for (int i = 1; i <= n; i++) {
// If integer is not in hashset, it is the missing integer
if (hashSet.find(i) == hashSet.end()) {
return i;
}
}
// If no integer is missing, return n+1
return n+1;
}
int main() {
int arr[] = {1, 2, 4, 6, 3, 7, 8};
int n = sizeof(arr) / sizeof(arr[0]);
int missingNumber = findMissingNumber(arr, n);
cout << "Missing number is: " << missingNumber << endl;
return 0;
}
Java
import java.util.HashSet;
public class Main {
public static int findMissingNumber(int[] arr, int n) {
HashSet<Integer> hashSet = new HashSet<Integer>();
// Add all elements of array to hashset
for (int i = 0; i < n-1; i++) {
hashSet.add(arr[i]);
}
// Check each integer from 1 to n
for (int i = 1; i <= n; i++) {
// If integer is not in hashset, it is the missing integer
if (!hashSet.contains(i)) {
return i;
}
}
// If no integer is missing, return n+1
return n+1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 4, 6, 3, 7, 8};
int n = arr.length;
int missingNumber = findMissingNumber(arr, n);
System.out.println("Missing number is: " + missingNumber);
}
}
Python
def find_missing_number(arr):
n = len(arr) + 1
hash_set = set(arr)
for i in range(1, n):
if i not in hash_set:
return i
return n
arr = [1, 2, 4, 6, 3, 7, 8]
missing_number = find_missing_number(arr)
print("Missing number is:", missing_number)
C#
using System;
using System.Collections.Generic;
class Program
{
static int FindMissingNumber(int[] arr, int n)
{
HashSet<int> hashSet = new HashSet<int>();
// Add all elements of array to hashset
for (int i = 0; i < n - 1; i++)
{
hashSet.Add(arr[i]);
}
// Check each integer from 1 to n
for (int i = 1; i <= n; i++)
{
// If integer is not in hashset, it is the missing integer
if (!hashSet.Contains(i))
{
return i;
}
}
// If no integer is missing, return n+1
return n + 1;
}
static void Main(string[] args)
{
int[] arr = { 1, 2, 4, 6, 3, 7, 8 };
int n = arr.Length;
int missingNumber = FindMissingNumber(arr, n);
Console.WriteLine("Missing number is: " + missingNumber);
}
}
Javascript
function findMissingNumber(arr, n) {
let hashSet = new Set();
// Add all elements of array to hashset
for (let i = 0; i < n - 1; i++) {
hashSet.add(arr[i]);
}
// Check each integer from 1 to n
for (let i = 1; i <= n; i++) {
// If integer is not in hashset, it is the missing integer
if (!hashSet.has(i)) {
return i;
}
}
// If no integer is missing, return n+1
return n + 1;
}
let arr = [1, 2, 4, 6, 3, 7, 8];
let n = arr.length;
let missingNumber = findMissingNumber(arr, n);
console.log("Missing number is: " + missingNumber);
OutputMissing number is: 5
Time Complexity: O(n), where n is the length of given array
Auxiliary Space: O(n)
Efficient approach: It 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.
Below is the implementation of the above approach:
C++
// A binary search based program to find the
// only missing number in a sorted array of
// distinct elements within limited range.
#include <iostream>
using namespace std;
int search(int ar[], int size)
{
// Extreme cases
if (ar[0] != 1)
return 1;
if (ar[size - 1] != (size + 1))
return size + 1;
int a = 0, b = size - 1;
int mid;
while ((b - a) > 1) {
mid = (a + b) / 2;
if ((ar[a] - a) != (ar[mid] - mid))
b = mid;
else if ((ar[b] - b) != (ar[mid] - mid))
a = mid;
}
return (ar[a] + 1);
}
int main()
{
int ar[] = { 1, 2, 3, 4, 5, 6, 8 };
int size = sizeof(ar) / sizeof(ar[0]);
cout << "Missing number:" << search(ar, size);
}
// This code is contributed by Pushpesh Raj
Java
// A binary search based program
// to find the only missing number
// in a sorted array of distinct
// elements within limited range.
import java.io.*;
class GFG {
static int search(int ar[], int size)
{
// Extreme cases
if (ar[0] != 1)
return 1;
if (ar[size - 1] != (size + 1))
return size + 1;
int a = 0, b = size - 1;
int mid = 0;
while ((b - a) > 1) {
mid = (a + b) / 2;
if ((ar[a] - a) != (ar[mid] - mid))
b = mid;
else if ((ar[b] - b) != (ar[mid] - mid))
a = mid;
}
return (ar[a] + 1);
}
// Driver Code
public static void main(String[] args)
{
int ar[] = { 1, 2, 3, 4, 5, 6, 8 };
int size = ar.length;
System.out.println("Missing number: "
+ search(ar, size));
}
}
// This code is contributed
// by inder_verma.
Python
# A binary search based program to find
# the only missing number in a sorted
# in a sorted array of distinct elements
# within limited range
def search(ar, size):
# Extreme cases
if(ar[0] != 1):
return 1
if(ar[size-1] != (size+1)):
return size+1
a = 0
b = size - 1
mid = 0
while b > a + 1:
mid = (a + b) // 2
if (ar[a] - a) != (ar[mid] - mid):
b = mid
elif (ar[b] - b) != (ar[mid] - mid):
a = mid
return ar[a] + 1
# Driver Code
a = [1, 2, 3, 4, 5, 6, 8]
n = len(a)
print("Missing number:", search(a, n))
# This code is contributed
# by Mohit Kumar
C#
// A binary search based program
// to find the only missing number
// in a sorted array of distinct
// elements within limited range.
using System;
class GFG {
static int search(int[] ar, int size)
{
// Extreme cases
if (ar[0] != 1)
return 1;
if (ar[size - 1] != (size + 1))
return size + 1;
int a = 0, b = size - 1;
int mid = 0;
while ((b - a) > 1) {
mid = (a + b) / 2;
if ((ar[a] - a) != (ar[mid] - mid))
b = mid;
else if ((ar[b] - b) != (ar[mid] - mid))
a = mid;
}
return (ar[a] + 1);
}
// Driver Code
static public void Main(String[] args)
{
int[] ar = { 1, 2, 3, 4, 5, 6, 8 };
int size = ar.Length;
Console.WriteLine("Missing number: "
+ search(ar, size));
}
}
// This code is contributed
// by Arnab Kundu
Javascript
<script>
// A binary search based program
// to find the only missing number
// in a sorted array of distinct
// elements within limited range.
function findMissing(arr) {
var size = arr.length;
//Extreme cases
if(ar[0]!=1)
return 1;
if(ar[size-1]!=(size+1))
return size+1;
var low = 0;
var high = arr.length;
while (low <= high) {
var mid = Math.floor((low+high)/2);
if ((arr[mid]-mid === 1) && (arr[mid+1]-(mid+1) === 2)) return arr[mid]+1;
if (arr[mid]-mid === 1) {
low = mid+1;
} else {
high = mid-1;
}
}
return -1;
}
// Driver Code
let ar = [1, 2, 3, 4, 5, 6, 8];
document.write("Missing number: " +findMissing(ar));
// This code is contributed by mohit kumar 29.
</script>
PHP
<?php
// A binary search based program to find the
// only missing number in a sorted array of
// distinct elements within limited range.
function search($ar, $size)
{
//Extreme cases
if($ar[0]!=1)
return 1;
if($ar[$size-1]!=($size+1))
return $size+1;
$a = 0;
$b = $size - 1;
$mid;
while (($b - $a) > 1)
{
$mid = (int)(($a + $b) / 2);
if (($ar[$a] - $a) != ($ar[$mid] -
$mid))
$b = $mid;
else if (($ar[$b] - $b) != ($ar[$mid] -
$mid))
$a = $mid;
}
return ($ar[$a] + 1);
}
// Driver Code
$ar = array(1, 2, 3, 4, 5, 6, 8 );
$size = sizeof($ar);
echo "Missing number: ",
search($ar, $size);
// This code is contributed by ajit.
?>
Time Complexity: O(log(N)), where N is the length of given array
Auxiliary Space: O(1)
Most Efficient approach (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, 4, 5, 6 };
int missing = findMissingNumber(numbers);
cout << "The missing number from the sorted array is: "
<< missing << endl;
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
// Function to find the missing number in a sorted array
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(4);
numbers.add(5);
numbers.add(6);
int missing = findMissingNumber(numbers);
System.out.println(
"The missing number from the sorted array is: "
+ missing);
}
}
// This code is contributed by Ayush Mishra
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 list
array_sum = sum(nums)
# Subtract and return the total sum with the sum of
# all elements in the list
missing_number = total_sum - array_sum
return missing_number
if __name__ == "__main__":
numbers = [1, 2, 4, 5, 6]
missing = find_missing_number(numbers)
print("The missing number from the sorted list is:", missing)
OutputThe missing number from the sorted array is: 3
Time Complexity : O(1)
Auxilary Space : O(1)
Share your thoughts in the comments
Please Login to comment...