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
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read