Find Missing Number in a given Array Using 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:

[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)

 

Support Django Central

If you appreciate my work, or if it has helped you along your journey. It would mean a lot to me if you could write a message on my wall and share a cup of coffee (or tea) with me.
Buy Me a Coffee at ko-fi.com

Leave a Comment