Find Missing Number in a given Array Using Python

2 min read

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:

[8]

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
author's image
Abhijeet Pal Author and Editor in Chief @djangocentral

Abhijeet is a full-stack software developer from India with a strong focus on backend and system design. He is driven by the need to create impactful solutions that add value to the internet in any way possible.

LinkedIn Twitter Github

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…
Read more →

3 min read

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…
Read more →

4 min read