- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find missing element in a sorted array of consecutive numbers in Python
Suppose we have an array A of n unique numbers, these n elements are present in the array in ascending order, but there is one missing element. We have to find the missing element.
So, if the input is like A = [1, 2, 3, 4, 5, 6, 7, 9], then the output will be 8.
To solve this, we will follow these steps −
n := size of A
left := 0
right := n - 1
mid := 0
while right > left , do
mid := left +(right - left) / 2
if A[mid] - mid is same as A[0], then
if A[mid + 1] - A[mid] > 1, then
return A[mid] + 1
otherwise,
left := mid + 1
otherwise,
if A[mid] - A[mid - 1] > 1, then
return A[mid] - 1
otherwise,
right := mid - 1
return -1
Example
Let us see the following implementation to get better understanding −
def search_missing_item(A): n = len(A) left, right = 0, n - 1 mid = 0 while (right > left): mid = left + (right - left) // 2 if (A[mid] - mid == A[0]): if (A[mid + 1] - A[mid] > 1): return A[mid] + 1 else: left = mid + 1 else: if (A[mid] - A[mid - 1] > 1): return A[mid] - 1 else: right = mid - 1 return -1 A = [1, 2, 3, 4, 5, 6, 7, 9] print(search_missing_item(A))
Input
[1, 2, 3, 4, 5, 6, 7, 9]
Output
8
- Related Articles
- Find missing element in a sorted array of consecutive numbers in C++
- Find missing numbers in a sorted list range in Python
- Missing Element in Sorted Array in C++
- k-th missing element in sorted array in C++
- Find position of an element in a sorted array of infinite numbers in C++
- Count of only repeated element in a sorted array of consecutive elements in C++
- Finding missing element in an array of numbers in JavaScript
- Find First and Last Position of Element in Sorted Array in Python
- Find the only missing number in a sorted array using C++
- What are the different ways to find missing numbers in a sorted array without any inbuilt functions using C#?
- Program to find missing numbers from two list of numbers in Python
- Single Element in a Sorted Array in C++
- Check If a Number Is Majority Element in a Sorted Array in Python
- Find four missing numbers in an array containing elements from 1 to N in Python
- Program to find concatenation of consecutive binary numbers in Python

Advertisements