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

Latest Articles

Latest from djangocentral

Capturing Query Parameters of request.get in Django

In Django, the request object contains a variety of information about the current HTTP request, including the query parameters. Query parameters are a way to pass additional information in the URL and are used to filter or sort data. The request object p…
Read more →

2 min read

Understanding related_name in Django Models

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the relat…
Read more →

2 min read