TipsMake

Write a program to find missing numbers in a sorted list using Python

In this article, TipsMake.com will learn with you how to write a program to find missing numbers in a sorted list using Python.

Problem : Given a sorted list of integers but some are missing, write a Python program to find all the missing integers.

Example :

Input : [1, 2, 4, 6, 7, 9, 10] Output : [3, 5, 8] Input : [5, 6, 10, 11, 13] Output : [7, 8, 9, 12]

In this article, TipsMake.com will learn with you how to write a program to find missing numbers in a sorted list using Python.

Method 1: Use List Comprehension

You can work around this with Python's built-in List Comprehension. Here is the sample code for your reference:

# Python3 program to Find missing # integers in list def find_missing(lst): max = lst[0] for i in lst : if i > max : max= i min = lst [0] for i in lst : if i < min: min = i missing = max+1 list1=[] for _ in lst : max = max -1 if max not in lst : list1.append(max) return list1 # Driver code lst = [1,5,4,6,8, 2,3, 7, 9, 10] print(find_missing(lst))

The returned result is:

[3, 5, 8]

Method 2: Use List Comprehension with zip()

Still similar to method 1, but you use zip() to shorten the code. Here is sample code:

# Python3 program to Find missing # integers in list def find_missing(lst): return [i for x, y in zip(lst, lst[1:]) for i in range(x + 1, y) if y - x > 1] # Driver code lst = [1, 2, 4, 6, 7, 9, 10] print(find_missing(lst))

The returned result is:

[3, 5, 8]

Method 3: Using set

Using Python's set is an efficient and simple way to find missing numbers in a list. We will convert the list to a set and simply output the difference between this set and the set of integers min to max.

Here is the sample code for your reference:

# Python3 program to Find missing # integers in list def find_missing(lst): return sorted(set(range(lst[0], lst[-1])) - set(lst)) # Driver code lst = [1, 2, 4, 6, 7, 9, 10, 12, 13, 15] print(find_missing(lst))

The returned result is:

[3, 5, 8, 11, 14]

Method 4: Use difference()

This is a similar approach to #3. However, with a slight difference, instead of using the "-" operator to find the difference between two sets, we can use the difference( ) of Python.

Here is sample code:

# Python3 program to Find missing # integers in list def find_missing(lst): start = lst[0] end = lst[-1] return sorted(set(range(start, end + 1)).difference(lst)) # Driver code lst = [1, 2, 4, 6, 7, 9, 10] print(find_missing(lst))

The returned result is:

[3, 5, 8]

Conclude

Finding the missing number in the sorted list is a frequently asked question by employers to check the qualifications of candidates. TipsMake.com hopes that this article will help you.

Discover more

python python programming
Jessica Tanner

Share by

Jessica Tanner
Update 27 June 2023