Find k-th missing element in increasing sequence in Java

In this tutorial, we will see how to find kth missing element in an increasing sequence that is not present in a given sequence in Java.

Finding the kth missing element in an increasing sequence that is not present in a given sequence in java

First let’s understand the question: So we are given two sequences or arrays, in which one is increasing inc[] and other is normal nor[], now we have to find the K-th missing element in the inc[] which is not present in the nor[].

Consider an increasing sequence, inc[] = { 4, 8, 12, 16, 20, 24, 28, 32, 36, 40 }
and a given sequence, nor[] = { 4, 12, 8, 20, 32, 40 }
let’s say, k = 4
Since, the numbers from the increasing sequence which are not present in the given sequence are 16, 24, 28 and 36 so the 4th missing element is 36.

Below is the code for the same example:

import java.util.*; 
  
class Example { 
  public static void main(String[] args) { 

    int inc[] = { 4, 8, 12, 16, 20, 24, 28, 32, 36, 40 }; 
    int nor[] = { 4, 12, 8, 20, 32, 40 }; 
    int k = 4;
    int element = 0; 
    LinkedHashSet<Integer> set = new LinkedHashSet<>(); 
    
    for (int i = 0; i < nor.length; i++) 
      set.add(nor[i]); 
    
    for (int j = 0; j < inc.length; j++)  
    { 
      if(!set.contains(inc[j]) )  
        element++; 
      if (element == k) {
        System.out.println(k+ "th mising element is: " + inc[j]); 
        break;
      }
    } 
  } 
}

Output:

4th missing element is: 36

Related article:

How to traverse through a HashSet in Java
Detect a loop in a LinkedList in Java

Leave a Reply

Your email address will not be published. Required fields are marked *