Python Program for k-th missing element in sorted array
Last Updated :
08 May, 2023
Given an increasing sequence a[], we need to find the K-th missing contiguous element in the increasing sequence which is not present in the sequence. If no k-th missing element is there output -1.
Examples :
Input : a[] = {2, 3, 5, 9, 10};
k = 1;
Output : 1
Explanation: Missing Element in the increasing
sequence are {1,4, 6, 7, 8}. So k-th missing element
is 1
Input : a[] = {2, 3, 5, 9, 10, 11, 12};
k = 4;
Output : 7
Explanation: missing element in the increasing
sequence are {1, 4, 6, 7, 8} so k-th missing
element is 7
Approach 1: Start iterating over the array elements, and for every element check if the next element is consecutive or not, if not, then take the difference between these two, and check if the difference is greater than or equal to given k, then calculate ans = a[i] + count, else iterate for next element.
Python3
# Function to find k-th
# missing element
def missingK(a, k, n) :
difference = 0
ans = 0
count = k
flag = 0
# iterating over the array
for i in range (0, n-1) :
difference = 0
# check if i-th and
# (i + 1)-th element
# are not consecutive
if ((a[i] + 1) != a[i + 1]) :
# save their difference
difference += (a[i + 1] - a[i]) - 1
# check for difference
# and given k
if (difference >= count) :
ans = a[i] + count
flag = 1
break
else :
count -= difference
# if found
if(flag) :
return ans
else :
return -1
# Driver code
# Input array
a = [1, 5, 11, 19]
# k-th missing element
# to be found in the array
k = 11
n = len(a)
# calling function to
# find missing element
missing = missingK(a, k, n)
print(missing)
# This code is contributed by
# Manish Shaw (manishshaw1)
Time Complexity :O(n), where n is the number of elements in the array.
Space Complexity: O(1) as no extra space has been used.
Approach 2:
Apply a binary search. Since the array is sorted we can find at any given index how many numbers are missing as arr[index] - (index+1). We would leverage this knowledge and apply binary search to narrow down our hunt to find that index from which getting the missing number is easier.
Below is the implementation of the above approach:
Python3
# Python3 program for above approach
# Function to find
# kth missing number
def missingK(arr, k):
n = len(arr)
l = 0
u = n - 1
mid = 0
while(l <= u):
mid = (l + u)//2;
numbers_less_than_mid = arr[mid] - (mid + 1);
# If the total missing number
# count is equal to k we can iterate
# backwards for the first missing number
# and that will be the answer.
if(numbers_less_than_mid == k):
# To further optimize we check
# if the previous element's
# missing number count is equal
# to k. Eg: arr = [4,5,6,7,8]
# If you observe in the example array,
# the total count of missing numbers for all
# the indices are same, and we are
# aiming to narrow down the
# search window and achieve O(logn)
# time complexity which
# otherwise would've been O(n).
if(mid > 0 and (arr[mid - 1] - (mid)) == k):
u = mid - 1;
continue;
# Else we return arr[mid] - 1.
return arr[mid]-1;
# Here we appropriately
# narrow down the search window.
if(numbers_less_than_mid < k):
l = mid + 1;
elif(k < numbers_less_than_mid):
u = mid - 1;
# In case the upper limit is -ve
# it means the missing number set
# is 1,2,..,k and hence we directly return k.
if(u < 0):
return k;
# Else we find the residual count
# of numbers which we'd then add to
# arr[u] and get the missing kth number.
less = arr[u] - (u + 1);
k -= less;
# Return arr[u] + k
return arr[u] + k;
# Driver Code
if __name__=='__main__':
arr = [2,3,4,7,11];
k = 5;
# Function Call
print("Missing kth number = "+ str(missingK(arr, k)))
# This code is contributed by rutvik_56.
OutputMissing kth number = 9
Time Complexity: O(logn), where n is the number of elements in the array.
Auxiliary Space: O(1) as no extra space has been used.
Please refer complete article on k-th missing element in sorted array for more details!
Similar Reads
Python heapq to find K'th smallest element in a 2D array Given an n x n matrix and integer k. Find the k'th smallest element in the given 2D array. Examples: Input : mat = [[10, 25, 20, 40], [15, 45, 35, 30], [24, 29, 37, 48], [32, 33, 39, 50]] k = 7 Output : 7th smallest element is 30 We will use similar approach like Kâth Smallest/Largest Element in Uns
3 min read
How to get the indices of the sorted array using NumPy in Python? We can get the indices of the sorted elements of a given array with the help of argsort() method. This function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as arr that would sort the arra
2 min read
Python | Find smallest element greater than K This problem involves searching through a list to identify the smallest number that is still larger than K. We will explore different methods to achieve this in Python In this article, we'll look at simple ways to find the smallest element greater than k in a list using Python.Using Binary SearchBin
3 min read
Python Set difference to find lost element from a duplicated array Given two arrays which are duplicates of each other except one element, that is one element from one of the array is missing, we need to find that missing element. Examples: Input: A = [1, 4, 5, 7, 9] B = [4, 5, 7, 9] Output: [1] 1 is missing from second array. Input: A = [2, 3, 4, 5 B = 2, 3, 4, 5,
1 min read
How to use numpy.argsort in Descending order in Python The numpy.argsort() function is used to conduct an indirect sort along the provided axis using the kind keyword-specified algorithm. It returns an array of indices of the same shape as arr, which would be used to sort the array. It refers to value indices ordered in ascending order. In this article,
4 min read
Python | Indices of Kth element value Sometimes, while working with records, we might have a problem in which we need to find all the indices of elements for a particular value at a particular Kth position of tuple. This seems to be a peculiar problem but while working with many keys in records, we encounter this problem. Let's discuss
4 min read