Write a Python Program to Find the Missing Element from the Given List
In this tutorial, we will write program to find the missing element from the given list within the range of 1 to N.
The problem statement is given an array of size N-1 such that it only contains distinct integers in the range of 1 to N. Find the missing element.
Example - 1
N = 5
A = [1,2,3,5]
Example - 2:
N = 10
A = [6,1,2,8,3,4,7,10,5]
We can solve this problem using the two approaches. Let's see the first approach.
Approach - 1: Sum of Integers
We can follow the below steps -
Let's see the following code.
The missing element is: 4
The above code, we create the find_missing_element() function which takes length of list and list of integer as arguments. We calculates the sum of integers from 1 to N using the formula, then sums the elements of the array to find the missing element by subtracting the sum of the array from the sum of integers. This solution has a time complexity of O(N) since it requires traversing the entire array.
Approach -2: Binary Search
We will solve this problem using the binary search algorithm. Below are the steps.
Let's see the following Python code.
The missing element is: 9
The optimized solution uses binary search to find the missing element more efficiently.
We first sort the array in ascending order, then initialize two pointers, left and right, to the first and last indices of the array, respectively.
We then calculate the middle index and determine whether the missing element is in the left or right half of the array.
We repeat this process until we find the missing element, which will be at the index pointed to by the left. This solution has a time complexity of O(log N) since we eliminate half of the array at each iteration.
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week