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, 10, 20, 40} Output: 32
Naive Approach: The simplest approach to solve the problem is to iterate through the array and calculate the sum of all the adjacent differences of the elements of the array.Â
Step by step algorithm:
- Initialize a variable count to 0.
- Traverse the array from index 0 to N-2.
- If the difference between a[i+1] and a[i] is greater than 1, increment count by (a[i+1] – a[i] – 1).
- Print count as the number of missing elements in the array.
C++
#include <iostream>using namespace std;Â
void countMissingNum(int a[], int N){Â Â Â Â int count = 0;Â Â Â Â for (int i = 0; i < N - 1; i++) {Â Â Â Â Â Â Â Â if (a[i+1] != a[i] + 1) {Â Â Â Â Â Â Â Â Â Â Â Â count += (a[i+1] - a[i] - 1);Â Â Â Â Â Â Â Â }Â Â Â Â }Â Â Â Â cout << count << endl;}Â
int main(){Â Â Â Â int arr[] = { 5, 10, 20, 40 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â countMissingNum(arr, N);Â Â Â Â return 0;}//This code is contributed by Zaid Khan |
Java
import java.util.Arrays;Â
class GFG {         // This function displays the count of the missing numbers    public static void countMissingNum(int[] a, int N) {        int count = 0;                 // Iterating over the array        for (int i = 0; i < N - 1; i++) {              // Checking if the consecutive number is not present            if (a[i + 1] != a[i] + 1) {                count += (a[i + 1] - a[i] - 1);            }        }        System.out.println(count);    }           // Driver code    public static void main(String[] args) {        int[] arr = { 5, 10, 20, 40 };        int N = arr.length;                     // Function call        countMissingNum(arr, N);    }} |
Python
# This function displays the count of the missing numbersdef CountMissingNum(a, N):Â Â Â Â count = 0Â
    # Iterating over the array    for i in range(N - 1):        # Checking if the consecutive number is not present        if a[i + 1] != a[i] + 1:            count += (a[i + 1] - a[i] - 1)         print(count)Â
# Driver codearr = [5, 10, 20, 40]N = len(arr)Â
# Function callCountMissingNum(arr, N) |
C#
using System;Â
class GFG{    // This function displays the count of the missing numbers    public static void CountMissingNum(int[] a, int N)    {        int count = 0;Â
        // Iterating over the array        for (int i = 0; i < N - 1; i++)        {            // Checking if the consecutive number is not present            if (a[i + 1] != a[i] + 1)            {                count += (a[i + 1] - a[i] - 1);            }        }        Console.WriteLine(count);    }Â
    // Driver code    public static void Main(string[] args)    {        int[] arr = { 5, 10, 20, 40 };        int N = arr.Length;Â
        // Function call        CountMissingNum(arr, N);    }} |
Javascript
// This function displays the count of the missing numbersfunction CountMissingNum(a, N) {let count = 0;Â
// Iterating over the arrayfor (let i = 0; i < N - 1; i++) {  // Checking if the consecutive number is not present  if (a[i + 1] !== a[i] + 1) {    count += (a[i + 1] - a[i] - 1);  }}console.log(count);}Â
// Driver codeconst arr = [5, 10, 20, 40];const N = arr.length;Â
// Function callCountMissingNum(arr, N); |
32
Time Complexity:O(N)Â
Auxiliary Space: O(1)Â
Efficient Approach: To optimize the above approach, the idea is to observe that the total count of numbers in the range of [arr[0], arr[N – 1]] is given by arr[N-1] – arr[0] + 1. Since the size of the array is N, the count of missing integers in the array is given by arr[N-1] – arr[0] + 1 – N. Below is the implementation of the above approach:Â
C++
// C++ Program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function that find the count of// missing numbers in array a[]void countMissingNum(int a[], int N){    // Calculate the count of missing    // numbers in the array    int count = a[N - 1] - a[0] + 1 - N;Â
    cout << count << endl;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 5, 10, 20, 40 };Â
    int N = sizeof(arr) / sizeof(arr[0]);Â
    countMissingNum(arr, N);Â
    return 0;} |
Java
// Java program for the above approachclass GFG{     // Function that find the count of// missing numbers in array a[]public static void countMissingNum(int[] a,                                int N){         // Calculate the count of missing    // numbers in the array    int count = a[N - 1] - a[0] + 1 - N;Â
    System.out.println(count);}Â
// Driver codepublic static void main(String[] args){Â Â Â Â int arr[] = { 5, 10, 20, 40 };Â
    int N = arr.length;Â
    countMissingNum(arr, N);}}Â
// This code is contributed by divyeshrabadiya07 |
Python3
# Python3 program for the above approachÂ
# Function that find the count of# missing numbers in array a[]def countMissingNum(a, N):         # Calculate the count of missing    # numbers in the array    count = a[N - 1] - a[0] + 1 - NÂ
    print(count)Â
# Driver Codearr = [ 5, 10, 20, 40 ]Â
N = len(arr)Â
countMissingNum(arr, N)Â
# This code is contributed by sanjoy_62 |
C#
// C# program for the above approachusing System;Â
class GFG{     // Function that find the count of// missing numbers in array a[]public static void countMissingNum(int[] a,                                int N){         // Calculate the count of missing    // numbers in the array    int count = a[N - 1] - a[0] + 1 - N;Â
    Console.Write(count);}Â
// Driver codepublic static void Main(string[] args){Â Â Â Â int []arr = { 5, 10, 20, 40 };Â Â Â Â int N = arr.Length;Â
    countMissingNum(arr, N);}}Â
// This code is contributed by rutvik_56 |
Javascript
// JS Program for the above approachÂ
// Function that find the count of// missing numbers in array a[]function countMissingNum(a, N){    // Calculate the count of missing    // numbers in the array    let count = a[N - 1] - a[0] + 1 - N;Â
    console.log(count);}Â
// Driver Codelet arr = [ 5, 10, 20, 40 ];let N = arr.length;countMissingNum(arr, N);Â
// This code is contributed by phasing17 |
32
Time Complexity: O(1)
Auxiliary Space: O(1)
Approach : Using Hashing
Steps:
- First, create a hash table.
- Insert all the elements of the array into it.
- After inserted all elements, iterate over the range of values between the first and last element of the array.
- If an element is not present in the hash table, then it is a missing number.
- Keep track of the count of missing numbers and return it as output.
Below is the implementation of the above approach:Â
C++
// C++ program of the above approachÂ
#include <iostream>#include <unordered_set>using namespace std;Â
// Function to count the number of missing elements in a// sorted arrayint countMissingNumbers(int arr[], int n){Â Â Â Â unordered_set<int> hashSet;Â Â Â Â for (int i = 0; i < n; i++) {Â Â Â Â Â Â Â Â hashSet.insert(arr[i]);Â Â Â Â }Â Â Â Â int first = arr[0];Â Â Â Â int last = arr[n - 1];Â Â Â Â int count = 0;Â Â Â Â for (int i = first; i <= last; i++) {Â Â Â Â Â Â Â Â if (hashSet.find(i) == hashSet.end()) {Â Â Â Â Â Â Â Â Â Â Â Â count++;Â Â Â Â Â Â Â Â }Â Â Â Â }Â Â Â Â return count;}Â
// Driver Codeint main(){Â
    int arr[] = { 5, 10, 20, 40 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << countMissingNumbers(arr, n) << endl;Â
    return 0;} |
Java
import java.util.HashSet;Â
class GFG {         // Function to count the number of missing elements in a    // sorted array    public static int countMissingNumbers(int[] arr, int n) {        HashSet<Integer> hashSet = new HashSet<Integer>();        for (int i = 0; i < n; i++) {            hashSet.add(arr[i]);        }        int first = arr[0];        int last = arr[n - 1];        int count = 0;        for (int i = first; i <= last; i++) {            if (!hashSet.contains(i)) {                count++;            }        }        return count;    }Â
    // Driver Code    public static void main(String[] args) {        int[] arr = { 5, 10, 20, 40 };        int n = arr.length;        System.out.println(countMissingNumbers(arr, n));    }}Â
Â
// by phasing17 |
Python3
# Function to count the number of missing elements in a# sorted arraydef countMissingNumbers(arr):Â Â Â Â hashSet = set(arr)Â Â Â Â first = arr[0]Â Â Â Â last = arr[-1]Â Â Â Â count = 0Â Â Â Â for i in range(first, last + 1):Â Â Â Â Â Â Â Â if i not in hashSet:Â Â Â Â Â Â Â Â Â Â Â Â count += 1Â Â Â Â return countÂ
# Driver Codeif __name__ == "__main__":Â Â Â Â arr = [5, 10, 20, 40]Â Â Â Â n = len(arr)Â Â Â Â print(countMissingNumbers(arr)) |
C#
using System;using System.Collections.Generic;Â
public class GFG{    // Function to count the number of missing elements in a    // sorted array    public static int CountMissingNumbers(int[] arr, int n)    {        HashSet<int> hashSet = new HashSet<int>();        for (int i = 0; i < n; i++)        {            hashSet.Add(arr[i]);        }        int first = arr[0];        int last = arr[n - 1];        int count = 0;        for (int i = first; i <= last; i++)        {            if (!hashSet.Contains(i))            {                count++;            }        }        return count;    }Â
    // Driver Code    public static void Main()    {        int[] arr = { 5, 10, 20, 40 };        int n = arr.Length;        Console.WriteLine(CountMissingNumbers(arr, n));    }}Â
// by phasing17 |
Javascript
function GFG(arr) {    // Create a Set to store the unique elements from     // the input array    const hashSet = new Set(arr);    const first = arr[0];    const last = arr[arr.length - 1];    let count = 0;    // Loop through the range of elements from     // first to last    for (let i = first; i <= last; i++) {        if (!hashSet.has(i)) {            count++;        }    }    // Return the count of missing elements    return count;}// Test the function with an example arrayconst arr = [5, 10, 20, 40];console.log(GFG(arr)); |
32
Time Complexity: O(n)
Auxiliary Space: O(n)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
