How to find the missing number in an array in python?

Problem Definition

Find the missing numbers in a given list or array using Python.

For example in the arr = [1,2,4,5] the integer '3' is the missing number.

There are multiple ways to solve this problem using Python. In this article, we will cover the most straightforward ones.

Algorithm

Step 1: Create an empty array for missing items

Step 2: Loop over the elements within the range of the first and last element of the array

Step 3: Compare the loop variable with the given array if the value is not present append it to the missing array

Note: The array must be sorted for this to work. Use arr.sort() on an unsorted array before feeding it to the program.

Solution 1

arr = [1,2,3,4,5,6,7,9,10]
missing_elements = []
for ele in range(arr[0], arr[-1]+1):
    if ele not in arr:
        missing_elements.append(ele)
print(missing_elements)

Output:

2. Using List Comprehension

arr = [1,2,3,4,5,7,6,9,10]
missing_elemnts = [item for item in range(arr[0], arr[-1]+1) if item not in arr]
print(missing_elemnts)

Output:

[8]

Using list comprehension we encapsulated the above solution in a single line.

3. Using Set()

Set() is a Python unordered mutable datatype that holds only unique values.

arr = [1,2,3,4,5,7,6,9,10]
missing_value = set(range(arr[0], arr[-1]+1)) - set(arr)
print(missing_value)

Output:

{8}

Here we created a set object of having values within the range of initial and final values of the provided array then compared it with the provided array to retrieve the missing value.

Instead of subtraction, we can also use the difference() method of the set().

set(range(arr[0], arr[-1]+1)).difference(arr)

PROGRAMS

Latest Articles

Latest from djangocentral

Django 4.1 adds async-compatible interface to QuerySet

The much-awaited pull request for an async-compatible interface to Queryset just got merged into the main branch of Django.Pull Request - https://github.com/django/django/pull/14843 The Django core team has been progressively adding async suppor…

Making Django Admin Jazzy With django-jazzmin

Django admin is undoubtedly one of the most useful apps of Django. Over the years there has been very little change in the admin app as far as the UX is concerned and it's not a bad thing at all. Django admin was designed to provide a simple and minimali…

©

djangocentral | Djangocentral is not associated with the DSF | Django is a registered trademark of the Django Software Foundation

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: The missing number between 1 to 8 is 5

Input: arr[] = {1, 2, 3, 5}, N = 5
Output: 4
Explanation: The missing number between 1 to 5 is 4

How to find the missing number in an array in python?

Approach 1 (Using Hashing):The idea behind the following approach is

The numbers will be in the range (1, N), an array of size N can be maintained to keep record of the elements present in the given array

  • Create a temp array temp[] of size n + 1 with all initial values as 0.
  • Traverse the input array arr[], and do following for each arr[i] 
    • if(temp[arr[i]] == 0) temp[arr[i]] = 1
  • Traverse temp[] and output the array element having value as 0 (This is the missing element).

Below is the implementation of the above approach:

C++

#include

using namespace std;

void findMissing(int arr[], int N)

{

    int i;

    int temp[N + 1];

    for(int i = 0; i <= N; i++){

      temp[i] = 0;

    }

    for(i = 0; i < N; i++){

      temp[arr[i] - 1] = 1;

    }

    int ans;

    for (i = 0; i <= N ; i++) {

        if (temp[i] == 0)

            ans = i  + 1;

    }

    cout << ans;

}

int main()

{

    int arr[] = { 1, 3, 7, 5, 6, 2 };

    int n = sizeof(arr) / sizeof(arr[0]);

    findMissing(arr, n);

}

Java

import java.io.*;

import java.util.*;

class GFG {

    public static void findMissing(int arr[], int N)

    {

        int i;

        int temp[] = new int[N + 1];

        for (i = 0; i <= N; i++) {

            temp[i] = 0;

        }

        for (i = 0; i < N; i++) {

            temp[arr[i] - 1] = 1;

        }

        int ans = 0;

        for (i = 0; i <= N; i++) {

            if (temp[i] == 0)

                ans = i + 1;

        }

        System.out.println(ans);

    }

    public static void main(String[] args)

    {

        int arr[] = { 1, 3, 7, 5, 6, 2 };

        int n = arr.length;

        findMissing(arr, n);

    }

}

Javascript

Time Complexity: O(N)
Auxiliary Space: O(N)

Approach 2 (Using summation of first N natural numbers): The idea behind the approach is to use the summation of the first N numbers.

Find the sum of the numbers in the range [1, N] using the formula N * (N+1)/2. Now find the sum of all the elements in the array and subtract it from the sum of the first N natural numbers. This will give the value of the missing element.

Follow the steps mentioned below to implement the idea:

  • Calculate the sum of the first N natural numbers as sumtotal= N*(N+1)/2.
  • Traverse the array from start to end.
    • Find the sum of all the array elements.
  • Print the missing number as SumTotal – sum of array

Below is the implementation of the above approach:

C++14

#include

using namespace std;

int getMissingNo(int a[], int n)

{

    int N = n + 1;

    int total = (N) * (N + 1) / 2;

    for (int i = 0; i < n; i++)

        total -= a[i];

    return total;

}

int main()

{

    int arr[] = { 1, 2, 3, 5 };

    int N = sizeof(arr) / sizeof(arr[0]);

    int miss = getMissingNo(arr, N);

    cout << miss;

    return 0;

}

C

#include

int getMissingNo(int a[], int n)

{

    int i, total;

    total = (n + 1) * (n + 2) / 2;

    for (i = 0; i < n; i++)

        total -= a[i];

    return total;

}

void main()

{

    int arr[] = { 1, 2, 3, 5 };

    int N = sizeof(arr) / sizeof(arr[0]);

    int miss = getMissingNo(arr, N);

    printf("%d", miss);

}

Java

import java.util.*;

import java.util.Arrays;

class GFG {

    public static int getMissingNo(int[] nums, int n)

    {

        int sum = ((n + 1) * (n + 2)) / 2;

        for (int i = 0; i < n; i++)

            sum -= nums[i];

        return sum;

    }

    public static void main(String[] args)

    {

        int[] arr = { 1, 2, 3, 5 };

        int N = arr.length;

        System.out.println(getMissingNo(arr, N));

    }

}

Python

def getMissingNo(arr, n):

    total = (n + 1)*(n + 2)/2

    sum_of_A = sum(arr)

    return total - sum_of_A

if __name__ == '__main__':

    arr = [1, 2, 3, 5]

    N = len(arr)

    miss = getMissingNo(arr, N)

    print(miss)

C#

using System;

class GFG {

    static int getMissingNo(int[] a, int n)

    {

        int total = (n + 1) * (n + 2) / 2;

        for (int i = 0; i < n; i++)

            total -= a[i];

        return total;

    }

    public static void Main()

    {

        int[] arr = { 1, 2, 3, 5 };

        int N = 4;

        int miss = getMissingNo(arr, N);

        Console.Write(miss);

    }

}

PHP

function getMissingNo ($a, $n)

{

    $total = ($n + 1) * ($n + 2) / 2;

    for ( $i = 0; $i < $n; $i++)

        $total -= $a[$i];

    return $total;

}

$arr = array(1, 2, 3, 5);

$N = 4;

$miss = getMissingNo($arr, $N);

echo($miss);

?>

Javascript

Time Complexity: O(N)
Auxiliary Space: O(1)

Modification for Overflow: The approach remains the same but there can be an overflow if N is large. 

In order to avoid integer overflow, pick one number from the range [1, N] and subtract a number from the given array (don’t subtract the same number twice). This way there won’t be any integer overflow.

Algorithm: 

  • Create a variable sum = 1 which will store the missing number and a counter variable c = 2.
  • Traverse the array from start to end.
    • Update the value of sum as sum = sum – array[i] + c and increment c by 1. This performs the task mentioned in the above idea]
  • Print the missing number as a sum.

Below is the implementation of the above approach:

C++

#include

using namespace std;

int getMissingNo(int a[], int n)

{

    int i, total = 1;

    for (i = 2; i <= (n + 1); i++) {

        total += i;

        total -= a[i - 2];

    }

    return total;

}

int main()

{

    int arr[] = { 1, 2, 3, 5 };

    int N = sizeof(arr) / sizeof(arr[0]);

    cout << getMissingNo(arr, N);

    return 0;

}

C

#include

int getMissingNo(int a[], int n)

{

    int i, total = 1;

    for (i = 2; i <= (n + 1); i++) {

        total += i;

        total -= a[i - 2];

    }

    return total;

}

void main()

{

    int arr[] = { 1, 2, 3, 5 };

    int N = sizeof(arr) / sizeof(arr[0]);

    printf("%d", getMissingNo(arr, N));

}

Java

class GFG {

    static int getMissingNo(int a[], int n)

    {

        int total = 1;

        for (int i = 2; i <= (n + 1); i++) {

            total += i;

            total -= a[i - 2];

        }

        return total;

    }

    public static void main(String[] args)

    {

        int[] arr = { 1, 2, 3, 5 };

        int N = arr.length;

        System.out.println(getMissingNo(arr, N));

    }

}

Python3

def getMissingNo(a, n):

    i, total = 0, 1

    for i in range(2, n + 2):

        total += i

        total -= a[i - 2]

    return total

if __name__ == '__main__':

    arr = [1, 2, 3, 5]

    N = len(arr)

    print(getMissingNo(arr, N))

C#

using System;

class GFG {

    static int getMissingNo(int[] a, int n)

    {

        int i, total = 1;

        for (i = 2; i <= (n + 1); i++) {

            total += i;

            total -= a[i - 2];

        }

        return total;

    }

    public static void Main()

    {

        int[] arr = { 1, 2, 3, 5 };

        int N = (arr.Length);

        Console.Write(getMissingNo(arr, N));

    }

}

Javascript

Time Complexity: O(N).  Only one traversal of the array is needed.
Auxiliary Space: O(1). No extra space is needed

Approach 3 (Using binary operations): This method uses the technique of XOR to solve the problem.  

XOR has certain properties 

  • Assume a1 ⊕ a2 ⊕ a3 ⊕ . . . ⊕ an = a and a1 ⊕ a2 ⊕ a3 ⊕ . . . ⊕ an-1 = b
  • Then a ⊕ b = an

Follow the steps mentioned below to implement the idea:

  • Create two variables a = 0 and b = 0
  • Run a loop from i = 1 to N:
    • For every index, update a as a = a ^ i
  • Now traverse the array from i = start to end.
    • For every index, update b as b = b ^ arr[i].
  • The missing number is a ^ b.

Below is the implementation of the above approach:

C++

#include

using namespace std;

int getMissingNo(int a[], int n)

{

    int x1 = a[0];

    int x2 = 1;

    for (int i = 1; i < n; i++)

        x1 = x1 ^ a[i];

    for (int i = 2; i <= n + 1; i++)

        x2 = x2 ^ i;

    return (x1 ^ x2);

}

int main()

{

    int arr[] = { 1, 2, 3, 5 };

    int N = sizeof(arr) / sizeof(arr[0]);

    int miss = getMissingNo(arr, N);

    cout << miss;

    return 0;

}

C

#include

int getMissingNo(int a[], int n)

{

    int i;

    int x1 = a[0];

    int x2 = 1;

    for (i = 1; i < n; i++)

        x1 = x1 ^ a[i];

    for (i = 2; i <= n + 1; i++)

        x2 = x2 ^ i;

    return (x1 ^ x2);

}

void main()

{

    int arr[] = { 1, 2, 3, 5 };

    int N = sizeof(arr) / sizeof(arr[0]);

    int miss = getMissingNo(arr, N);

    printf("%d", miss);

}

Java

class Main {

    static int getMissingNo(int a[], int n)

    {

        int x1 = a[0];

        int x2 = 1;

        for (int i = 1; i < n; i++)

            x1 = x1 ^ a[i];

        for (int i = 2; i <= n + 1; i++)

            x2 = x2 ^ i;

        return (x1 ^ x2);

    }

    public static void main(String args[])

    {

        int arr[] = { 1, 2, 3, 5 };

        int N = arr.length;

        int miss = getMissingNo(arr, N);

        System.out.println(miss);

    }

}

Python3

def getMissingNo(a, n):

    x1 = a[0]

    x2 = 1

    for i in range(1, n):

        x1 = x1 ^ a[i]

    for i in range(2, n + 2):

        x2 = x2 ^ i

    return x1 ^ x2

if __name__ == '__main__':

    arr = [1, 2, 3, 5]

    N = len(arr)

    miss = getMissingNo(arr, N)

    print(miss)

C#

using System;

class GFG {

    static int getMissingNo(int[] a, int n)

    {

        int x1 = a[0];

        int x2 = 1;

        for (int i = 1; i < n; i++)

            x1 = x1 ^ a[i];

        for (int i = 2; i <= n + 1; i++)

            x2 = x2 ^ i;

        return (x1 ^ x2);

    }

    public static void Main()

    {

        int[] arr = { 1, 2, 3, 5 };

        int N = 4;

        int miss = getMissingNo(arr, N);

        Console.Write(miss);

    }

}

PHP

function getMissingNo($a, $n)

{

    $x1 = $a[0];

    $x2 = 1;

    for ($i = 1; $i < $n; $i++)

        $x1 = $x1 ^ $a[$i];

    for ($i = 2; $i <= $n + 1; $i++)

        $x2 = $x2 ^ $i;    

    return ($x1 ^ $x2);

}

$arr = array(1, 2, 3, 5);

$N = 4;

$miss = getMissingNo($arr, $N);

echo($miss);

?>

Javascript

Time Complexity: O(N) 
Auxiliary Space: O(1) 

Approach 4 (UsingCyclic Sort): The idea behind it is as follows:

All the given array numbers are sorted and in the range of 1 to n-1. If the range is 1 to N  then the index of every array element will be the same as (value – 1).

Follow the below steps to implement the idea:

  • Use cyclic sort to sort the elements in linear time.
  • Now traverse from i = 0 to the end of the array:
    • If arr[i] is not the same as i+1 then the missing element is (i+1).
  • If all elements are present then N is the missing element in the range [1, N].

Below is the implementation of the above approach.

C++

#include

using namespace std;

int getMissingNo(int a[], int n)

{

    int i = 0;

    while (i < n) {

        int correct = a[i] - 1;

        if (a[i] < n && a[i] != a[correct]) {

            swap(a[i], a[correct]);

        }

        else {

            i++;

        }

    }

    for (int i = 0; i < n; i++) {

        if (i != a[i] - 1) {

            return i + 1;

        }

    }

    return n;

}

int main()

{

    int arr[] = { 1, 2, 3, 5 };

    int N = sizeof(arr) / sizeof(arr[0]);

    int miss = getMissingNo(arr, N);

    cout << (miss);

    return 0;

}

Java

import java.util.*;

public class MissingNumber {

    public static void main(String[] args)

    {

        int[] arr = { 1, 2, 3, 5 };

        int N = arr.length;

        int ans = getMissingNo(arr, N);

        System.out.println(ans);

    }

    static int getMissingNo(int[] arr, int n)

    {

        int i = 0;

        while (i < n) {

            int correctpos = arr[i] - 1;

            if (arr[i] < n && arr[i] != arr[correctpos]) {

                swap(arr, i, correctpos);

            }

            else {

                i++;

            }

        }

        for (int index = 0; index < arr.length; index++) {

            if (arr[index] != index + 1) {

                return index + 1;

            }

        }

        return arr.length;

    }

    static void swap(int[] arr, int i, int correctpos)

    {

        int temp = arr[i];

        arr[i] = arr[correctpos];

        arr[correctpos] = temp;

    }

}

Python3

def getMissingNo(arr, n) :

    i = 0;

    while (i < n) :

        correctpos = arr[i] - 1;

        if (arr[i] < n and arr[i] != arr[correctpos]) :

            arr[i],arr[correctpos] = arr[correctpos], arr[i]

        else :

            i += 1;

    for index in range(n) :

        if (arr[index] != index + 1) :

            return index + 1;

    return n;

if __name__ == "__main__" :

    arr = [ 1, 2, 3, 5 ];

    N = len(arr);

    print(getMissingNo(arr, N));

C#

using System;

class GFG {

    static int getMissingNo(int[] arr, int n)

    {

        int i = 0;

        while (i < n) {

            int correctpos = arr[i] - 1;

            if (arr[i] < n && arr[i] != arr[correctpos]) {

                swap(arr, i, correctpos);

            }

            else {

                i++;

            }

        }

        for (int index = 0; index < n; index++) {

            if (arr[index] != index + 1) {

                return index + 1;

            }

        }

        return n;

    }

    static void swap(int[] arr, int i, int correctpos)

    {

        int temp = arr[i];

        arr[i] = arr[correctpos];

        arr[correctpos] = temp;

    }

    public static void Main()

    {

        int[] arr = { 1, 2, 4, 5, 6 };

        int N = arr.Length;

        int ans = getMissingNo(arr, N);

        Console.Write(ans);

    }

}

Javascript

Time Complexity: O(N), requires (N-1) comparisons
Auxiliary Complexity: O(1) 

Approach 5 (Use elements as Index and mark the visited places as negative): Use the below idea to get the approach

Traverse the array. While traversing, use the absolute value of every element as an index and make the value at this index as negative to mark it visited. To find missing, traverse the array again and look for a positive value.

Follow the steps to solve the problem:

  • Traverse the given array
    • If the absolute value of current element is greater than size of the array, then continue.
    • else multiply the (absolute value of (current element) – 1)th index with -1.
  • Initialize a variable ans = size + 1.
  • Traverse the array and follow the steps:
    • if the value is positive assign ans = index + 1
  • Print ans as the missing value.

Below is the implementation of the above approach:

C++

#include

using namespace std;

void findMissing(int arr[], int size)

{

    int i;

    for (i = 0; i < size; i++) {

        if(abs(arr[i]) - 1 == size){

          continue;

        }

        int ind = abs(arr[i]) - 1;

        arr[ind] *= -1;

    }

    int ans = size + 1;

    for (i = 0; i < size; i++) {

        if (arr[i] > 0)

            ans = i  + 1;

    }

    cout << ans;

}

int main()

{

    int arr[] = { 1, 3, 7, 5, 6, 2 };

    int n = sizeof(arr) / sizeof(arr[0]);

    findMissing(arr, n);

}

Java

import java.io.*;

import java.util.*;

class GFG {

  public static void findMissing(int arr[], int size)

  {

    int i;

    for (i = 0; i < size; i++) {

      if (Math.abs(arr[i]) - 1 == size) {

        continue;

      }

      int ind = Math.abs(arr[i]) - 1;

      arr[ind] *= -1;

    }

    int ans = size + 1;

    for (i = 0; i < size; i++) {

      if (arr[i] > 0)

        ans = i + 1;

    }

    System.out.println(ans);

  }

  public static void main(String[] args)

  {

    int arr[] = { 1, 3, 7, 5, 6, 2 };

    int n = arr.length;

    findMissing(arr, n);

  }

}

Python3

def findMissing(a, size):

    for i in range(0, n):

        if (abs(arr[i]) - 1 == size):

            continue

        ind = abs(arr[i]) - 1

        arr[ind] *= -1

    ans = size + 1

    for i in range(0, n):

        if (arr[i] > 0):

            ans = i + 1

    print(ans)

if __name__ == '__main__':

    arr = [1, 3, 7, 5, 6, 2]

    n = len(arr)

    findMissing(arr, n)

Javascript

Time Complexity: O(N) 
Auxiliary Space: O(1) 


How do you find the missing number in an array of numbers?

Simple Approach.
Calculate the summation of first N natural numbers as Total = N * (N + 1) / 2..
Create a variable sum to store the summation of elements of the array..
Iterate the array from start to end..
Updating the value of sum as sum = sum + array[i].
Print the missing number as the Total – sum..

How do you find missing elements in an array?

Follow the steps mentioned below to implement the idea:.
Calculate the sum of the first N natural numbers as sumtotal= N*(N+1)/2..
Traverse the array from start to end. Find the sum of all the array elements..
Print the missing number as SumTotal – sum of array..

How do you find the missing number in a Python sequence?

Algorithm.
Step 1: Create an empty array for missing items..
Step 2: Loop over the elements within the range of the first and last element of the array..
Step 3: Compare the loop variable with the given array if the value is not present append it to the missing array..
Note: The array must be sorted for this to work. ... .
Output:.

How do you find multiple missing numbers in an array in Python?

To find the multiple missing elements run a loop inside it and see if the diff is less than arr[i] – i then print the missing element i.e., i + diff. Now increment the diff as the difference is increased now. Repeat from step 2 until all the missing numbers are not found.