Open In App

Missing in a Sorted Array of Natural Numbers

Last Updated : 21 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a sorted array arr[] of n-1 integers, these integers are in the range of 1 to n. There are no duplicates in the array. One of the integers is missing in the array. Find the missing integer. 
Examples: 

Input : arr[] = [1, 2, 3, 4, 6, 7, 8]
Output : 5
Explanation: The missing integer in the above array is 5

Input : arr[] = [1, 2, 3, 4, 5, 6, 8, 9]
Output : 7
Explanation: The missing integer in the above array is 7

[Naive Approach] - Nested Loops - O(n^2) Time and O(1) Space

The idea is to use two nested loops, where the outer one iterate from 1 to n, and inner one iterate for each of the array arr[] elements, if the value in outer loop in not found in array arr[], return the value, else iterate to the next value.

C++
#include <iostream>
#include <vector>
using namespace std;

int missingNumber(vector<int> &arr) {
    int n = arr.size() + 1;

    // Iterate from 1 to n and check
    // if the current number is present
    for(int i = 1; i <= n; i++){
        bool found = false;
        for(int j = 0; j < n - 1; j++){
            if(arr[j] == i) {
                found = true;
                break;
            }
        }

        // If the current number is not present
        if(!found)
            return i;
    }
    return -1;
}

int main(){
    vector<int> arr = {1, 2, 3, 4, 6, 7, 8};
    cout << missingNumber(arr);
    return 0;
}
Java
class GfG {

    static int missingNumber(int[] arr) {
        int n = arr.length + 1;

        // Iterate from 1 to n and check
        // if the current number is present
        for (int i = 1; i <= n; i++) {
            boolean found = false;
            for (int j = 0; j < arr.length; j++) {
                if (arr[j] == i) {
                    found = true;
                    break;
                }
            }

            // If the current number is not present
            if (!found)
                return i;
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 6, 7, 8};
        System.out.println(missingNumber(arr));
    }
}
Python
def missingNumber(arr):
    n = len(arr) + 1

    # Iterate from 1 to n and check
    # if the current number is present
    for i in range(1, n + 1):
        found = False
        for j in range(len(arr)):
            if arr[j] == i:
                found = True
                break

        # If the current number is not present
        if not found:
            return i
    return -1

if __name__ == "__main__":
    arr = [1, 2, 3, 4, 6, 7, 8]
    print(missingNumber(arr))
C#
using System;

class GfG {

    static int missingNumber(int[] arr) {
        int n = arr.Length + 1;

        // Iterate from 1 to n and check
        // if the current number is present
        for (int i = 1; i <= n; i++) {
            bool found = false;
            for (int j = 0; j < arr.Length; j++) {
                if (arr[j] == i) {
                    found = true;
                    break;
                }
            }

            // If the current number is not present
            if (!found)
                return i;
        }
        return -1;
    }

    public static void Main(string[] args) {
        int[] arr = {1, 2, 3, 4, 6, 7, 8};
        Console.WriteLine(missingNumber(arr));
    }
}
JavaScript
function missingNumber(arr) {
    let n = arr.length + 1;

    // Iterate from 1 to n and check
    // if the current number is present
    for (let i = 1; i <= n; i++) {
        let found = false;
        for (let j = 0; j < arr.length; j++) {
            if (arr[j] === i) {
                found = true;
                break;
            }
        }

        // If the current number is not present
        if (!found)
            return i;
    }
    return -1;
}

// Driver Code
let arr = [1, 2, 3, 4, 6, 7, 8];
console.log(missingNumber(arr));

Output
5

[Better approach 1] - Comparing the difference between index and elements - O(n) Time and O(1) Space

The idea for this approach is to compare the index and element on that index of the sorted array. If the difference between the index and element on that index is greater than 1 then the missing element is index + 1. If the difference between the index and the element for all index is 1 then the missing element is n.

C++
#include <iostream>
#include <vector>
using namespace std;

int missingNumber(vector<int> &arr) {
    int n = arr.size()+1; 
    
    // checking the difference between 
    // index and element
    for (int i = 0; i < n-1; i++) {
        
        // if difference between index and element 
        // is not 1
        if( arr[i] != i+1)

        return i+1; 
    }
    
    // If the diference between index and 
    // element on that inidex
    // for all index is 1 
    return n;
}


int main() {
    vector<int> arr = {1, 2, 3, 4, 6, 7, 8};
    cout << missingNumber(arr);
    return 0;
}
Java
import java.util.List;
import java.util.Arrays;

public class GfG {
    static int missingNumber(int arr[]) {
        
        int n = arr.length+1; 
        
        // checking the difference between 
        // index and element
        for (int i = 0; i < n-1; i++) {
            
        // if difference between index and element 
        // is not 1
            if (arr[i] != i + 1)
                return i + 1;
        }
        
        // If the diference between index and 
        // element on that inidex
        // for all index is 1 
        return n;
    }


    public static void main(String[] args) {
        int arr[]  = {1, 2, 3, 4, 6, 7, 8};
        System.out.println( missingNumber(arr));
    }
}
Python
def missingNumber(arr):
    
    n = len(arr)+1
    
    # checking the difference between 
    # index and element
    for i in range(n-1):
        
        # if difference between index and element 
        # is not 1
        if arr[i] != i + 1:
            return i + 1
            
    # If the diference between index and 
    # element on that inidex
    # for all index is 1             
    return n

if __name__ == "__main__":
    arr = [1, 2, 3, 4, 6, 7, 8]
    print( missingNumber(arr))
C#
using System;

class GfG {
    static int missingNumber(int[] arr) {
        
        int n = arr.Length + 1;
        
        // checking the difference between 
        // index and element
        for (int i = 0; i < n - 1; i++) {
            
            // if difference between index and element 
            // is not 1
            if (arr[i] != i + 1)
                return i + 1;
        }
        
        // If the difference between index and 
        // element on that index is always 1         
        return n;
    }

    static void Main() {
        int[] arr = { 1, 2, 3, 4, 6, 7, 8 };
        Console.WriteLine(missingNumber(arr));
    }
}
JavaScript
function missingNumber(arr) {
    let n = arr.length+1;
    
    // checking the difference between 
    // index and element
    for (let i = 0; i < n-1; i++) {
        
        // if difference between index and element 
        // is not 1
        if (arr[i] !== i + 1)
        return i + 1;
    }
    
    // If the diference between index and 
    // element on that inidex
    // for all index is 1     
    return n;
}

// Driver Code
let arr = [1, 2, 3, 4, 6, 7, 8];
console.log(missingNumber(arr));

Output
5

[Better approach 2] - Using Formula for Sum of n terms- O(n) Time and O(1) Space

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.

C++
#include <iostream>
#include <vector>

using namespace std;

int missingNumber(vector<int>& arr) {
    
    // Calculate the total sum
    int n = arr.size() + 1;
    int totalSum = n * (n + 1) / 2;

    // Calculate sum of all elements in the given array
    int arraySum = 0;
    for (int num : arr) {
        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> arr = { 1, 2, 3, 4, 6, 7, 8 };
    cout << missingNumber(arr);

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class GfG {
    
    static int missingNumber(int arr[]) {
        
        // Calculate the total sum
        int n = arr.length + 1;
        int totalSum = n * (n + 1) / 2;

        // Calculate sum of all elements in the given array
        int arraySum = 0;
        for (int num : arr) {
            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) {
        int arr[] = { 1, 2, 3, 4, 6, 7, 8 };
        System.out.println(missingNumber(arr));
    }
}
Python
def missingNumber(arr):
  
    # Calculate the total sum
    n = len(arr) + 1
    totalSum = n * (n + 1) // 2

    # Calculate sum of all elements in the given list
    arraySum = sum(arr)

    # Subtract and return the missing number
    missingNumber = totalSum - arraySum

    return missingNumber

if __name__ == "__main__":
    arr = [1, 2, 3, 4, 6, 7, 8]
    print(missingNumber(arr))
C#
using System;
using System.Linq;

class GfG {
    static int missingNumber(int[] arr) {
        
        // Calculate the total sum
        int n = arr.Length + 1;
        int totalSum = (n * (n + 1)) / 2;

        // Calculate sum of all elements in the given array
        int arraySum = arr.Sum();

        // Subtract and return the total sum with the sum of
        // all elements in the array
        int missingNumber = totalSum - arraySum;

        return missingNumber;
    }

    static void Main() {
        int[] arr = { 1, 2, 3, 4, 6, 7, 8 };
        Console.WriteLine(missingNumber(arr));
    }
}
JavaScript
function missingNumber(arr) {

    // Calculate the total sum
    let n = arr.length + 1;
    let totalSum = (n * (n + 1)) / 2;

    // Calculate sum of all elements in the given array
    let arraySum = arr.reduce((sum, num) => sum + num, 0);

    // Subtract and return the total sum with the sum of
    // all elements in the array
    let missingNumber = totalSum - arraySum;

    return missingNumber;
}

// Driver Code
let arr = [1, 2, 3, 4, 6, 7, 8 ];
console.log(missingNumber(arr));

Output
5

Expected Approach - Using Binary Search - O(log(n)) Time and O(1) Space

The idea is that in a perfectly consecutive sequence starting from 1, the difference between each element and its index is always 1.
When a number is missing, this difference stays 1 before the missing number and becomes 2 after it.
By using binary search, we find the point where this shift occurs. The missing number is one more than the element just before the shift.

C++
#include <iostream>
#include <vector>
using namespace std;

int missingNumber(vector<int> &arr) {
    int n = arr.size();
    
    // Extreme cases
    if (arr[0] != 1)
        return 1;
    if (arr[n - 1] != (n + 1))
        return n + 1;
        
    //implementing binary search
    int lo = 0, hi = n - 1;
    int mid;
    while ((hi - lo) > 1) {
        mid = (lo + hi) / 2;
        if ((arr[lo] - lo) != (arr[mid] - mid))
            hi = mid;
        else if ((arr[hi] - hi) != (arr[mid] - mid))
            lo = mid;
    }
    return (arr[lo] + 1);
}

int main() {
    vector<int> arr = { 1, 2, 3, 4, 6, 7, 8 };
    cout << missingNumber(arr);
}
Java
public class GfG {
    static int missingNumber(int[] arr) {
        int n = arr.length;

        // Extreme cases
        if (arr[0] != 1) {
            return 1;
        }
        if (arr[n - 1] != (n + 1)) {
            return n + 1;
        }

        // implementing binary search
        int lo = 0, hi = n - 1;
        while ((hi - lo) > 1) {
            int mid = (lo + hi) / 2;
            if ((arr[lo] - lo) != (arr[mid] - mid)) {
                hi = mid;
            } else if ((arr[hi] - hi) != (arr[mid] - mid)) {
                lo = mid;
            }
        }
        return (arr[lo] + 1);
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 6, 7, 8};
        System.out.println(missingNumber(arr));
    }
}
Python
def missingNumber(arr):
    n = len(arr)
    
    # Extreme cases
    if arr[0] != 1:
        return 1
    if arr[n - 1] != n + 1:
        return n + 1
        
    # Implementing binary search
    lo, hi = 0, n - 1
    while hi - lo > 1:
        mid = (lo + hi) // 2
        if arr[lo] - lo != arr[mid] - mid:
            hi = mid
        elif arr[hi] - hi != arr[mid] - mid:
            lo = mid
    return arr[lo] + 1

if __name__ == "__main__":
    arr = [1, 2, 3, 4, 6, 7, 8]
    print(missingNumber(arr))
C#
using System;

public class GfG {
    
    static int missingNumber(int[] arr) {
        int n = arr.Length;

        // Extreme cases
        if (arr[0] != 1) {
            return 1;
        }
        if (arr[n - 1] != (n + 1)) {
            return n + 1;
        }

        // implementing binary search
        int lo = 0, hi = n - 1;
        while ((hi - lo) > 1) {
            int mid = (lo + hi) / 2;
            if ((arr[lo] - lo) != (arr[mid] - mid)) {
                hi = mid;
            } else if ((arr[hi] - hi) != (arr[mid] - mid)) {
                lo = mid;
            }
        }
        return (arr[lo] + 1);
    }

    public static void Main(string[] args) {
        int[] arr = {1, 2, 3, 4, 6, 7, 8};
        Console.WriteLine(missingNumber(arr));
    }
}
JavaScript
function missingNumber(arr) {
    const n = arr.length;
    
    // Extreme cases
    if (arr[0] !== 1) return 1;
    if (arr[n - 1] !== (n + 1)) return n + 1;
        
    // implementing binary search
    let lo = 0, hi = n - 1;
    let mid;
    while ((hi - lo) > 1) {
        mid = Math.floor((lo + hi) / 2);
        if ((arr[lo] - lo) !== (arr[mid] - mid)) hi = mid;
        else if ((arr[hi] - hi) !== (arr[mid] - mid)) lo = mid;
    }
    return (arr[lo] + 1);
}

// Driver Code
const arr = [1, 2, 3, 4, 6, 7, 8];
console.log(missingNumber(arr));

Output
5

Article Tags :
Practice Tags :

Similar Reads