Java 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.
Java
// Java program to check for
// even or odd
import java.io.*;
import java.util.*;
public class GFG {
// Function to find k-th
// missing element
static int missingK(int []a, int k,
int n)
{
int difference = 0,
ans = 0, count = k;
boolean flag = false;
// iterating over the array
for(int i = 0 ; i < n - 1; i++)
{
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 = true;
break;
}
else
count -= difference;
}
}
// if found
if(flag)
return ans;
else
return -1;
}
// Driver code
public static void main(String args[])
{
// Input array
int []a = {1, 5, 11, 19};
// k-th missing element
// to be found in the array
int k = 11;
int n = a.length;
// calling function to
// find missing element
int missing = missingK(a, k, n);
System.out.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:
Java
// Java program for above approach
public class GFG
{
// Function to find
// kth missing number
static int missingK(int[] arr, int k)
{
int n = arr.length;
int l = 0, u = n - 1, mid;
while(l <= u)
{
mid = (l + u)/2;
int 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 && (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;
}
else if(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.
int less = arr[u] - (u + 1);
k -= less;
// Return arr[u] + k
return arr[u] + k;
}
// Driver code
public static void main(String[] args)
{
int[] arr = {2,3,4,7,11};
int k = 5;
// Function Call
System.out.println("Missing kth number = "+ missingK(arr, k));
}
}
// This code is contributed by divyesh072019.
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
Java Program to Print the kth Element in the Array We need to print the element at the kth position in the given array. So we start the program by taking input from the user about the size of an array and then all the elements of that array. Now by entering the position k at which you want to print the element from the array, the program will print
2 min read
Java Program for Last duplicate element in a sorted array We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7} Output : Last index: 4 Last duplicate item: 6 Inpu
2 min read
Java Program to Print the Smallest Element in an Array Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. Example: arr1[] = {2 , -1 , 9 , 10} output : -1 arr2[] = {0, -10, -13, 5} output : -13 We need to find and print the smallest value
3 min read
Java Program for Sorting all array elements except one Given an array, a positive integer, sort the array in ascending order such that the element at index K in the unsorted array stays unmoved and all other elements are sorted. Examples: Input : arr[] = {10, 4, 11, 7, 6, 20} k = 2; Output : arr[] = {4, 6, 11, 7, 10, 20} Input : arr[] = {30, 20, 10} k =
3 min read
Java Program to Find the K'th largest element in a stream Given an infinite stream of integers, find the k'th largest element at any point of time.Example: Input: stream[] = {10, 20, 11, 70, 50, 40, 100, 5, ...} k = 3 Output: {_, _, 10, 11, 20, 40, 50, 50, ...} Extra space allowed is O(k). Recommended: Please solve it on "PRACTICE" first, before moving on
4 min read
Java Program to Find k maximum elements of array in original order Given an array arr[] and an integer k, we need to print k maximum elements of given array. The elements should printed in the order of the input.Note : k is always less than or equal to n. Examples: Input : arr[] = {10 50 30 60 15} k = 2 Output : 50 60 The top 2 elements are printed as per their app
4 min read
Java Program to Sort the Elements of an Array in Ascending Order Here, we will sort the array in ascending order to arrange elements from smallest to largest, i.e., ascending order. So the easy solution is that we can use the Array.sort method. We can also sort the array using Bubble sort.1. Using Arrays.sort() MethodIn this example, we will use the Arrays.sort()
2 min read
Java Program to Find the Mth element of the Array after K left rotations Given non-negative integers K, M, and an array arr[] with N elements find the Mth element of the array after K left rotations. Examples: Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1Output: 5Explanation:Â The array after first left rotation a1[ ] = {4, 5, 23, 3}The array after second left rotation a2[ ]
3 min read
Java Program to Sort the Elements of an Array in Descending Order Here, we will sort the array in descending order to arrange elements from largest to smallest. The simple solution is to use Collections.reverseOrder() method. Another way is sorting in ascending order and reversing.1. Using Collections.reverseOrder()In this example, we will use Collections.reverseO
2 min read
Java Program to Remove Duplicate Elements From the Array Given an array, the task is to remove the duplicate elements from an array. The simplest method to remove duplicates from an array is using a Set, which automatically eliminates duplicates. This method can be used even if the array is not sorted.Example:Java// Java Program to Remove Duplicate // Ele
6 min read