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

Find the Missing Number

Last Updated : 21 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[] of size N-1 with integers in the range of [1, N], the task is to find the missing number from the first N integers.

Note: There are no duplicates in the list.

Examples: 

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

Input: arr[] = {1, 2, 3, 5}, N = 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] Using Hashing – O(n) time and O(n) auxiliary space

The very basic idea is to use an array to store the frequency of each element in the given array. The number with a frequency of 0 is the missing number.

C++
// C++ program to Find the missing element

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

int missingNumber(int n, vector<int>& arr)
{

    // 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;
        }
    }

    // Edge case handling (though problem guarantees a
    // solution)
    return -1;
}

/* Driver code */
int main()
{
    vector<int> arr = { 1, 2, 3, 5 };
    int n = 5;
    cout << missingNumber(n, arr);
}
Java
import java.util.Arrays;

public class Main {
    public static int missingNumber(int n, int[] arr)
    {
        // Create hash array of size n+1
        int[] hash = new int[n + 1];

        // 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;
            }
        }

        // Edge case handling (though problem guarantees a
        // solution)
        return -1;
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 5 };
        int n = 5;
        System.out.println(missingNumber(n, arr));
    }
}
Python
def missing_number(n, arr):
    # Create hash array of size n+1
    hash = [0] * (n + 1)

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

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

    # Edge case handling (though problem guarantees a solution)
    return -1


# Driver code
arr = [1, 2, 3, 5]
n = 5
print(missing_number(n, arr))
C#
using System;

public class Program {
    public static int MissingNumber(int n, int[] arr)
    {
        // Create hash array of size n+1
        int[] hash = new int[n + 1];

        // 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;
            }
        }

        // Edge case handling (though problem guarantees a
        // solution)
        return -1;
    }

    public static void Main()
    {
        int[] arr = { 1, 2, 3, 5 };
        int n = 5;
        Console.WriteLine(MissingNumber(n, arr));
    }
}
JavaScript
function missingNumber(n, arr) {

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

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

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

    // Edge case handling (though problem guarantees a solution)
    return -1;
}

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

Output
4

Time Complexity: O(n), where n is the length of given array
Auxiliary Space: O(n)

[Expected Approach-1] Using Sum of N terms Formula – O(n) time and O(1) auxiliary space

An efficient approach is to use summation formula. As we know that the sum of the first N natural numbers is given by the formula N * (N + 1) / 2. Compute this sum and subtract the sum of all elements in the array from it to get the missing number.

Detailed Explanation:

  • Compute the sum of the first N natural numbers as expected sum using the formula.
  • Calculate the sum of the given array elements.
  • Subtract the sum of the array elements from the expected sum to find the missing number.

Code Implementation:

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

int missingNumber(int n, vector<int>& arr)
{
    // 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;
}

// Driver code
int main()
{
    vector<int> arr = { 1, 2, 3, 5 };
    int n = 5;
    cout << missingNumber(n, arr);
    return 0;
}
Java
public class Main {
    public static int missingNumber(int n, int[] arr)
    {
        int sum = 0;

        // Calculate the sum of array elements
        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 };
        int n = 5;
        System.out.println(missingNumber(n, arr));
    }
}
Python
def missing_number(n, arr):
    sum_arr = sum(arr)
    
    # Calculate the expected sum
    expected_sum = (n * (n + 1)) // 2
    
    # Return the missing number
    return expected_sum - sum_arr


# Driver code
arr = [1, 2, 3, 5]
n = 5
print(missing_number(n, arr))
C#
using System;

public class Program {
    public static int MissingNumber(int n, int[] arr)
    {
        int sum = 0;

        // Calculate the sum of array elements
        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()
    {
        int[] arr = { 1, 2, 3, 5 };
        int n = 5;
        Console.WriteLine(MissingNumber(n, arr));
    }
}
JavaScript
function missingNumber(n, arr) {
    let sum = 0;

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

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

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

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

Output
4

Time Complexity: O(n), where n is the length of given array
Auxiliary Space: O(1)

[Expected Approach-2] Using XOR Operation – O(n) time and O(1) auxiliary space

Another efficient approach is to use the XOR operation. The approach is based on the idea that XOR of a number with itself is 0, and XOR of a number with 0 is the number itself. This means that if we find XOR of first N natural numbers and then take XOR of each array elements with this, then the resultant will be the missing number.

Using these properties, the approach can be understood as::

  • First find XOR all numbers in the range [1, N]
  • Then XOR all elements of the array with the XOR(1, N).
  • The result will be the missing number.

Code Implementation:

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

// Function to get the missing number
int missingNumber(int n, vector<int>& arr)
{
    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;
}

// Driver Code
int main()
{
    vector<int> arr = { 1, 2, 3, 5 };
    int n = 5;

    // Function call
    int miss = missingNumber(n, arr);
    cout << miss;
    return 0;
}
Java
public class Main {
    public static int missingNumber(int n, int[] arr)
    {
        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;
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 5 };
        int n = 5;
        System.out.println(missingNumber(n, arr));
    }
}
Python
def missing_number(n, arr):
    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

# Driver code
arr = [1, 2, 3, 5]
n = 5
print(missing_number(n, arr))
C#
using System;

public class Program {
    public static int MissingNumber(int n, int[] arr)
    {
        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;
    }

    public static void Main()
    {
        int[] arr = { 1, 2, 3, 5 };
        int n = 5;
        Console.WriteLine(MissingNumber(n, arr));
    }
}
JavaScript
function missingNumber(n, arr) {
    let xor1 = 0, 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];
const n = 5;
console.log(missingNumber(n, arr));

Output
4

Time Complexity: O(n), where n is the length of given array
Auxiliary Space: O(1) 



Previous Article
Next Article

Similar Reads

Find the smallest missing number
Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array. Examples: Input: {0, 1, 2, 6, 9}, n = 5, m = 10 Output: 3 Input: {4, 5, 10, 11}, n = 4, m = 12 Output: 0 Input: {0, 1, 2, 3}, n = 4, m = 5 Output: 4 Input: {0, 1, 2, 3, 4, 5, 6, 7, 10},
15 min read
Find the one missing number in range
Given an array of size n. It is also given that range of numbers is from smallestNumber to smallestNumber + n where smallestNumber is the smallest number in array. The array contains number in this range but one number is missing so the task is to find this missing number. Examples: Input: arr[] = {13, 12, 11, 15}Output: 14 Input: arr[] = {33, 36,
9 min read
Find the smallest positive number missing from an unsorted array : Hashing Implementation
Given an unsorted array with both positive and negative elements including 0. The task is to find the smallest positive number missing from the array in O(N) time. Examples: Input: arr[] = {-5, 2, 0, -1, -10, 15} Output: 1 Input: arr[] = {0, 1, 2, 3, 4, 5} Output: 6 Input: arr[] = {1, 1, 1, 0, -1, -2} Output: 2 We can use hashing to solve this prob
5 min read
Find the smallest positive number missing from an unsorted array | Set 3
Given an unsorted array with both positive and negative elements. The task is to find the smallest positive number missing from the array. Examples: Input: arr[] = {2, 3, 7, 6, 8, -1, -10, 15} Output: 1 Input: arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 } Output: 4 Input: arr[] = {1, 1, 0, -1, -2} Output: 2 Approach : We have already discussed some of the
6 min read
Find the missing number in range [1, N*M+1] represented as Matrix of size N*M
Given an N x M matrix mat[][] where all elements are natural numbers starting from 1 and are continuous except 1 element, find that element. Examples: Input: mat[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 11, 12, 13}}N = 3, M = 4Output: 10Explanation: Missing number is 10 at row no 3. Input: mat[][] = {{1, 2, 3}, {5, 6, 7}, {8, 9, 10}} N = 3, M = 3Outp
15+ min read
Find the missing number in Arithmetic Progression
Given an array that represents elements of arithmetic progression in order. One element is missing in the progression, find the missing number. Examples: Input: arr[] = {2, 4, 8, 10, 12, 14} Output: 6 Input: arr[] = {1, 6, 11, 16, 21, 31}; Output: 26Recommended PracticeMissing element of APTry It! A Simple Solution is to linearly traverse the array
15+ min read
Find the smallest positive number missing from an unsorted array | Set 2
Given an unsorted array with both positive and negative elements. Find the smallest positive number missing from the array in O(n) time using constant extra space. It is allowed to modify the original array. Examples: Input: {2, 3, 7, 6, 8, -1, -10, 15} Output: 1 Input: { 2, 3, -7, 6, 8, 1, -10, 15 } Output: 4 Input: {1, 1, 0, -1, -2} Output: 2 Rec
12 min read
Find the missing number in Geometric Progression
Given an array that represents elements of geometric progression in order. One element is missing in the progression, find the missing number. It may be assumed that one term is always missing and the missing term is not first or last of series. Examples: Input : arr[] = {1, 3 , 27, 81} Output : 9 Input : arr[] = {4, 16, 64, 1024}; Output : 256 A S
7 min read
Find the missing number in a string of numbers with no separator
Given a string consisting of some numbers, not separated by any separator. The numbers are positive integers and the sequence increases by one at each number except the missing number. The task is to find the missing number. The numbers will have no more than six digits. Print -1 if the input sequence is not valid. Examples: Input : 89101113 Output
10 min read
Find missing number in another array which is shuffled copy
Given an array 'arr1' of n positive integers. Contents of arr1[] are copied to another array 'arr2', but numbers are shuffled and one element is removed. Find the missing element(without using any extra space and in O(n) time complexity). Examples : Input : arr1[] = {4, 8, 1, 3, 7}, arr2[] = {7, 4, 3, 1} Output : 8 Input : arr1[] = {12, 10, 15, 23,
6 min read
Find the missing number in a sorted array of limited range
Given a sorted array of size n and given that there are numbers from 1 to n+1 with one missing, the missing number is to be found. It may be assumed that array has distinct elements. Examples: Input : 1 3 4 5 6Output : 2 Input : 1 2 3 4 5 7 8 9 10Output : 6 Recommended: Please try your approach on {IDE} first, before moving on to the solution.We tr
10 min read
Find the only missing number in a sorted array
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 : 2Input : ar[] = {1, 2, 3, 4, 5, 7, 8}Output : 6A 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
9 min read
Most Efficient Way to Find a Missing Number in an array
Have you wondered which is the most efficient way for a popular problem to find a missing Number? well in this post we are going to discuss this phenomenon in brief. First, let's discuss the problem statement: Given an array of numbers from 1 to N (both inclusive). The size of the array is N-1. The numbers are randomly added to the array, there is
7 min read
Find the Missing Number in a sorted array
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
11 min read
Find the smallest positive number missing from an unsorted array | Set 1
Given an unsorted array arr[] with both positive and negative elements, the task is to find the smallest positive number missing from the array. Note: You can modify the original array. Examples: Input: arr[] = {2, 3, 7, 6, 8, -1, -10, 15}Output: 1 Input: arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }Output: 4 Input: arr[] = {1, 1, 0, -1, -2}Output: 2 Naiv
15+ min read
Javascript Program for Find the smallest missing number
Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array. Examples: Input: {0, 1, 2, 6, 9}, n = 5, m = 10 Output: 3 Input: {4, 5, 10, 11}, n = 4, m = 12 Output: 0 Input: {0, 1, 2, 3}, n = 4, m = 5 Output: 4 Input: {0, 1, 2, 3, 4, 5, 6, 7, 10},
4 min read
Find the missing integer in an array if mean is given
Given an array of size N-1 and the mean of N elements (one element is not given). We need to find the missing value X in the array. Examples: Input : a[] = {2, 4, 20}, Mean = 9Output : Missing Element = 10 Explanation : Mean of (2, 4, 20, 10) is (2 + 4 + 20 + 10)/4 = 9 Let x be the missing element Mean = (a1 + a2 + a3.. + X + ..an)/N. So (a1 + a2 +
4 min read
Find n-variables from n sum equations with one missing
You are given an array a[] of n values as a[1], a[2]...a[n] which are part of n-equations in n-variables where equations are as: Eqn1 => X2 + X3 +.....+Xn = a1 Eqn2 => X1 + X3 +.....+Xn = a2 Eqni => X1 + X2 +...+Xi-1 + Xi+1..+Xn = ai Eqnn => X1 + X2 +.....+Xn-1 = anAs you have n-equations in n-variables find the value of all variables(X
6 min read
Find the missing digit x from the given expression
Given an alphanumeric string, consisting of a single alphabet X, which represents an expression of the form: A operator B = C where A, B and C denotes integers and the operator can be either of +, -, * or / The task is to evaluate the missing digit X present in any of the integers A, B and C such that the given expression holds to be valid. Example
9 min read
Find the missing value from the given equation a + b = c
Given an equation of the form: a + b = c Out of which any one of the terms [Tex]a [/Tex], [Tex]b [/Tex]or [Tex]c [/Tex]is missing. The task is to find the missing term. Examples: Input: 2 + 6 = ? Output: 8 Input: ? + 3 =6 Output: 3 Approach: Missing numbers can be found simply using the equation [Tex]a + b = c [/Tex]. First, we will find two known
7 min read
Find the missing elements from 1 to M in given N ranges
Given N segments as ranges [L, R] where ranges are non-intersecting and non-overlapping. The task is to find all number between 1 to M that doesn't belong to any of the given ranges. Examples: Input : N = 2, M = 6 Ranges: [1, 2] [4, 5] Output : 3, 6 Explanation: Only 3 and 6 are missing from the above ranges. Input : N = 1, M = 5 Ranges: [2, 4] Out
8 min read
Find the missing elements from 1 to M in given N ranges | Set-2
Given an integer m and n ranges (e.g. [a, b]) which are intersecting and overlapping. The task is to find all the number within the range that doesn’t belong to any of the given ranges. Examples: Input: m = 6, ranges = {{1, 2}, {4, 5}} Output: 3 6 As only 3 and 6 are missing from the given ranges. Input: m = 5, ranges = {{2, 4}} Output: 1 5 Approac
14 min read
Find missing element in a sorted array of consecutive numbers
Given an array arr[] of n distinct integers. Elements are placed sequentially in ascending order with one element missing. The task is to find the missing element.Examples: Input: arr[] = {1, 2, 4, 5, 6, 7, 8, 9} Output: 3Input: arr[] = {-4, -3, -1, 0, 1, 2} Output: -2Input: arr[] = {1, 2, 3, 4} Output: -1 No element is missing. Principles: Look fo
7 min read
Find missing elements from an Array with duplicates
Given an array arr[] of size N having integers in the range [1, N] with some of the elements missing. The task is to find the missing elements. Note: There can be duplicates in the array. Examples: Input: arr[] = {1, 3, 3, 3, 5}, N = 5Output: 2 4Explanation: The numbers missing from the list are 2 and 4All other elements in the range [1, 5] are pre
12 min read
Find temperature of missing days using given sum and average
Given integers x and y which denotes the average temperature of the week except for days Day1 and Day2 respectively, and the sum of the temperature of Day1 and Day2 as S, the task is to find the temperature of the days Day1 and Day2.Examples: Input: x = 15, y = 10, S = 50 Output: Day1 = 10, Day2 = 40 Explanation: The average of week excluding Day1
5 min read
Find all missing numbers from a given sorted array
Given a sorted array arr[] of N integers, The task is to find the multiple missing elements in the array between the ranges [arr[0], arr[N-1]]. Examples: Input: arr[] = {6, 7, 10, 11, 13}Output: 8 9 12 Explanation: The elements of the array are present in the range of the maximum and minimum array element [6, 13]. Therefore, the total values will b
13 min read
Find the missing digit in given product of large positive integers
Given two large integers in form of strings A and B and their product also in form of string C such that one digit of the product is replaced with X, the task is to find the replaced digit in the product C. Examples: Input: A = 51840, B = 273581, C = 1418243x040Output: 9Explanation:The product of integer A and B is 51840 * 273581 = 14182439040. On
11 min read
Find all duplicate and missing numbers in given permutation array of 1 to N
Given an array arr[] of size N consisting of the first N natural numbers, the task is to find all the repeating and missing numbers over the range [1, N] in the given array. Examples: Input: arr[] = {1, 1, 2, 3, 3, 5}Output: Missing Numbers: [4, 6]Duplicate Numbers: [1, 3]Explanation:As 4 and 6 are not in arr[] Therefore they are missing and 1 is r
8 min read
Find the missing value from Array B formed by adding some value X to Array A
Given two arrays arr1[] and arr2[] of size N and N - 1 respectively. Each value in arr2[] is obtained by adding a hidden value say X to any arr1[i] for N-1 times, which means for any i, arr1[i]+X is not included in arr2[] that is the missing value in arr2[]. The task is to find both the hidden value X and the missing value which is not picked from
10 min read
Find K missing numbers from given Array in range [1, M] such that total average is X
Given an array arr[] of integers of size N where each element can be in the range [1, M], and two integers X and K. The task is to find K possible numbers in range [1, M] such that the average of all the (N + K) numbers is equal to X. If there are multiple valid answers, any one is acceptable. Examples: Input: arr[] = {3, 2, 4, 3}, M = 6, K = 2, X
6 min read