The Wayback Machine - https://web.archive.org/web/20250317113547/https://www.geeksforgeeks.org/find-the-missing-number/
Open In App

Find the Missing Number

Last Updated : 05 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given an array arr[] of size n-1 with distinct integers in the range of [1, n]. This array represents a permutation of the integers from 1 to n with one element missing. Find the missing element in the array.

Examples: 

Input: arr[] = [1, 2, 4, 6, 3, 7, 8]
Output: 5
Explanation: Here the size of the array is 7, so the range will be [1, 8]. The missing number between 1 to 8 is 5

Input: arr[] = [1, 2, 3, 5]
Output: 4
Explanation: Here the size of the array is 4, so the range will be [1, 5]. The missing number between 1 to 5 is 4

[Naive Approach] – 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++
// C++ program to find the
// missing number in the array
#include<bits/stdc++.h>
using namespace std;


// Function to find the missing number
int missingNumber(vector<int>& nums) {
    int n = nums.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(nums[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, 5};
    cout<<missingNumber(arr);
    return 0;
}
C
// C program to find the
// missing number in the array
#include <stdio.h>
#include <stdbool.h>

// Function to find the missing number
int missingNumber(int nums[], int n) {
    int size = n + 1;

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

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

int main() {
    int arr[] = {1, 2, 3, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d", missingNumber(arr, n));
    return 0;
}
Java
// Java program to find the
// missing number in the array
class GfG {

    // Function to find the missing number
    static int missingNumber(int[] nums) {
        int n = nums.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 < nums.length; j++) {
                if (nums[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, 5};
        System.out.println(missingNumber(arr));
    }
}
Python
# Python program to find the
# missing number in the array

# Function to find the missing number
def missingNumber(nums):
    n = len(nums) + 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(nums)):
            if nums[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, 5]
  print(missingNumber(arr))
C#
// C# program to find the
// missing number in the array
using System;

class GfG {

    // Function to find the missing number
    static int MissingNumber(int[] nums) {
        int n = nums.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 < nums.Length; j++) {
                if (nums[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, 5};
        Console.WriteLine(MissingNumber(arr));
    }
}
JavaScript
// JavaScript program to find the
// missing number in the array

// Function to find the missing number
function missingNumber(nums) {
    let n = nums.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 < nums.length; j++) {
            if (nums[j] === i) {
                found = true;
                break;
            }
        }

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

// Main function
let arr = [1, 2, 3, 5];
console.log(missingNumber(arr));

Output
4

[Better Approach] – Using Hashing – O(n) Time and O(n) Space

The idea is to use an auxiliary array hash[] to store the frequency of each element in the given array arr[]. The number with frequency 0 is the missing number.

C++
// C++ program to find the missing number

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

int missingNumber(vector<int> &arr) {

    int n = arr.size() + 1;

    // Create hash array of size n+1
    vector<int> hash(n + 1, 0);

    // Store frequencies of elements
    for (int i = 0; i < n - 1; i++) {
        hash[arr[i]]++;
    }

    // Find the missing number
    for (int i = 1; i <= n; i++) {
        if (hash[i] == 0) {
            return i;
        }
    }
    return -1;
}

int main() {
    vector<int> arr = {1, 2, 3, 5};
    int res = missingNumber(arr);
    cout << res << endl;
    return 0;
}
Java
//java program to find the missing number

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

        // Create hash array of size n+1
        int[] hash = new int[n + 1];

        // Store frequencies of elements
        for (int i = 0; i < arr.length; i++) {
            hash[arr[i]]++;
        }

        // Find the missing number
        for (int i = 1; i <= n; i++) {
            if (hash[i] == 0) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr
            = { 1, 2, 3, 5 };  
        int res = missingNumber(arr);
        System.out.println(res);  
    }
}
Python
# Python program to find the missing number

def missingNumber(arr):
    n = len(arr) + 1   

    # Create hash array of size n+1
    hashArr = [0] * (n + 1)

    # Store frequencies of elements
    for num in arr:
        hashArr[num] += 1

    # Find the missing number
    for i in range(1, n + 1):
        if hashArr[i] == 0:
            return i

    return -1

if __name__ == "__main__":
  arr = [1, 2, 3, 5]   
  result = missingNumber(arr)
  print(result)  
C#
// C# program to find the missing number

using System;

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

        // Create hash array of size n+1
        int[] hash = new int[n + 1];

        // Store frequencies of elements
        foreach(int num in arr) { hash[num]++; }

        // Find the missing number
        for (int i = 1; i <= n; i++) {
            if (hash[i] == 0) {
                return i;
            }
        }

        return -1;
    }

    static void Main() {
        int[] arr = { 1, 2, 3, 5 };
        int res = missingNumber(arr);
        Console.WriteLine(res);
    }
}
JavaScript
// JavaScript program to find the missing number

function missingNumber(arr) {
    const n = arr.length + 1;  

    // Create hash array of size n+1
    const hashArr = new Array(n + 1).fill(0);

    // Store frequencies of elements
    for (let i = 0; i < arr.length; i++) {
        hashArr[arr[i]]++;
    }

    // Find the missing number
    for (let i = 1; i <= n; i++) {
        if (hashArr[i] === 0) {
            return i;
        }
    }

    return -1;
}

// Driver Code
const arr = [ 1, 2, 3, 5 ];  
const res = missingNumber(arr);
console.log(res);  

Output
4

[Expected Approach-1] – Using Sum of n terms Formula – O(n) Time and O(1) Space

The sum of the first n natural numbers is given by the formula (n * (n + 1)) / 2. The idea is to compute this sum and subtract the sum of all elements in the array from it to get the missing number.

C++
// C++ program to find the missing number

#include <bits/stdc++.h>
using namespace std;

int missingNumber(vector<int> &arr) {

    int n = arr.size() + 1;
  
    // Calculate the sum of array elements
    int sum = 0;
    for (int i = 0; i < n - 1; i++) {
        sum += arr[i];
    }

    // Calculate the expected sum
    int expectedSum = (n * (n + 1)) / 2;

    // Return the missing number
    return expectedSum - sum;
}

int main() {
    vector<int> arr = {1, 2, 3, 5};
    cout << missingNumber(arr);
    return 0;
}
Java
// Java program to find the missing number  

class GfG {

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

        // Calculate the sum of array elements
        int sum = 0;
        for (int i = 0; i < n - 1; i++) {
            sum += arr[i];
        }

        // Calculate the expected sum
        int expectedSum = (n * (n + 1)) / 2;

        // Return the missing number
        return expectedSum - sum;
    }

    public static void main(String[] args) {
        int[] arr = { 1, 2, 3, 5 };

        System.out.println(missingNumber(arr));  
    }
}
Python
# Python program to find the missing number

def missingNumber(arr):
    n = len(arr) + 1

    # Calculate the sum of array elements
    totalSum = sum(arr)

    # Calculate the expected sum
    expectedSum = (n * (n + 1)) // 2

    # Return the missing number
    return expectedSum - totalSum

if __name__ == "__main__":
  arr = [1, 2, 3, 5]
  print(missingNumber(arr))  
C#
// C# program to find the missing number

using System;

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

        // Calculate the sum of array elements
        int totalSum = 0;
        foreach (int num in arr) {
            totalSum += num;
        }

        // Calculate the expected sum
        int expectedSum = (n * (n + 1)) / 2;

        // Return the missing number
        return expectedSum - totalSum;
    }

    static void Main() {
        int[] arr = { 1, 2, 3, 5 };
        Console.WriteLine(missingNumber(arr));  
    }
}
JavaScript
// Javascript program to find the missing number

function missingNumber(arr) {
    let n = arr.length + 1;

    // Calculate the sum of array elements
    let totalSum = 0;
    for (let i = 0; i < arr.length; i++) {
        totalSum += arr[i];
    }

    // Calculate the expected sum
    let expectedSum = (n * (n + 1)) / 2;

    // Return the missing number
    return expectedSum - totalSum;
}

// Driver Code
const arr = [1, 2, 3, 5];
console.log(missingNumber(arr));   

Output
4

[Expected Approach-2] Using XOR Operation – O(n) Time and O(1) Space

XOR of a number with itself is 0 i.e. x ^ x = 0 and the given array arr[] has numbers in range [1, n]. This means that the result of XOR of first n natural numbers with the XOR of all the array elements will be the missing number. To do so, calculate XOR of first n natural numbers and XOR of all the array arr[] elements, and then our result will be the XOR of both the resultant values.

C++
// C++ program to find the missing number

#include <bits/stdc++.h>
using namespace std;
 
int missingNumber( vector<int>& arr) {
    int n= arr.size()+1;
    int xor1 = 0, xor2 = 0;

    // XOR all array elements
    for (int i = 0; i < n - 1; i++) {
        xor2 ^= arr[i];
    }

    // XOR all numbers from 1 to n
    for (int i = 1; i <= n; i++) {
        xor1 ^= i;
    }

    // Missing number is the XOR of xor1 and xor2
    return xor1 ^ xor2;
}

 
int main() {
    vector<int> arr = { 1, 2, 3, 5 };
    int res = missingNumber( arr);
    cout << res;
    return 0;
}
Java
// Java program to find the missing number 

class GfG {
      static int missingNumber( int[] arr) {
        int xor1 = 0, xor2 = 0;
        int n= arr.length+1;

        // XOR all array elements
        for (int i = 0; i < n - 1; i++) {
            xor2 ^= arr[i];
        }

        // XOR all numbers from 1 to n
        for (int i = 1; i <= n; i++) {
            xor1 ^= i;
        }

        // Missing number is the XOR of xor1 and xor2
        return xor1 ^ xor2;
    }

    public static void main(String[] args) {
        int[] arr = { 1, 2, 3, 5 };
        System.out.println(missingNumber(arr));
    }
}
Python
 # Python program to find the missing number
  
def missingNumber(arr):
    n = len(arr) + 1
    xor1 = 0
    xor2 = 0

    # XOR all array elements
    for num in arr:
        xor2 ^= num

    # XOR all numbers from 1 to n
    for i in range(1, n + 1):
        xor1 ^= i

    # Missing number is the XOR of xor1 and xor2
    return xor1 ^ xor2

if __name__ == "__main__":
  arr = [1, 2, 3, 5]
  res = missingNumber(arr)
  print(res)
C#
// C# program to find the missing number

using System;

class GfG {
    
      static int missingNumber(int[] arr) {
        int n = arr.Length + 1;
        int xor1 = 0;
        int xor2 = 0;

        // XOR all array elements
        foreach (var num in arr) {
            xor2 ^= num;
        }

        // XOR all numbers from 1 to n
        for (int i = 1; i <= n; i++) {
            xor1 ^= i;
        }

        // Missing number is the XOR of xor1 and xor2
        return xor1 ^ xor2;
    }

    static void Main(string[] args)  {
        int[] arr = { 1, 2, 3, 5 };
        int res = missingNumber(arr);
        Console.WriteLine(res);
    }
}
JavaScript
 // JavaScript program to find the missing number
 
function missingNumber(arr) {
    const n = arr.length + 1;
    let xor1 = 0;
    let xor2 = 0;

    // XOR all array elements
    for (let i = 0; i < n - 1; i++) {
        xor2 ^= arr[i];
    }

    // XOR all numbers from 1 to n
    for (let i = 1; i <= n; i++) {
        xor1 ^= i;
    }

    // Missing number is the XOR of xor1 and xor2
    return xor1 ^ xor2;
}

// Driver Code
const arr = [ 1, 2, 3, 5 ];
console.log(missingNumber(arr));

Output
4


Next Article

Similar Reads

three90RightbarBannerImg