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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read