k-th missing element in sorted array

10 Jun, 2022
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.
C++
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; // Function to find k-th// missing elementint missingK(int a[], int k,             int n){    int difference = 0,        ans = 0, count = k;    bool flag = 0;       //case when first number is not 1    if (a[0] != 1){      difference = a[0]-1;      if (difference >= count)          return count;      count -= difference;      }         // 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 = 1;                    break;                }            else                count -= difference;        }    }         // if found    if(flag)        return ans;    else        return  -1;} // Driver codeint main(){    // Input array    int a[] = {1, 5, 11, 19};         // k-th missing element    // to be found in the array    int k = 11;    int n = sizeof(a) / sizeof(a[0]);         // calling function to    // find missing element    int missing = missingK(a, k, n);         cout << missing << endl;         return 0;}
// Java program to check for// even or oddimport 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;                   //case when first number is not 1        if (a[0] != 1){          difference = a[0]-1;          if (difference >= count)              return count;          count -= difference;          }               // 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)
# Function to find k-th# missing elementdef missingK(a, k, n) :     difference = 0    ans = 0    count = k    flag = 0         #case when first number is not 1    if a[0] != 1:      difference = a[0]-1      if difference >= count:        return count      count -= difference         # 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 arraya = [1, 5, 11, 19] # k-th missing element# to be found in the arrayk = 11n = len(a) # calling function to# find missing elementmissing = missingK(a, k, n) print(missing) # This code is contributed by# Manish Shaw (manishshaw1)
// C# program to check for// even or oddusing System;using System.Collections.Generic; 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;        bool flag = false;                 //case when first number is not 1        if (a[0] != 1){          difference = a[0]-1;          if (difference >= count)              return count;          count -= difference;          }                 // 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()    {                 // 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);                 Console.Write(missing);    } } // This code is contributed by// Manish Shaw (manishshaw1)
<?php// Function to find k-th// missing elementfunction missingK(&$a, $k, $n){    $difference = 0;    $ans = 0;    $count = $k;    $flag = 0;         // iterating over the array    for($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 = 1;                    break;                }            else                $count -= $difference;        }    }         // if found    if($flag)        return $ans;    else        return -1;} // Driver Code // Input array$a = array(1, 5, 11, 19); // k-th missing element// to be found in the array$k = 11;$n = count($a); // calling function to// find missing element$missing = missingK($a, $k, $n); echo $missing; // This code is contributed by Manish Shaw// (manishshaw1)?>
<script>     // Javascript program to check for// even or odd // Function to find k-th// missing elementfunction missingK(a, k, n){    let difference = 0, ans = 0, count = k;    let flag = false;         //case when first number is not 1    if (a[0] != 1){      difference = a[0]-1;      if (difference >= count){          return count;          }      count -= difference;      }          // iterating over the array    for(let 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 // Input arraylet a = [ 1, 5, 11, 19 ]; // k-th missing element// to be found in the arraylet k = 11;let n = a.length; // Calling function to// find missing elementlet missing = missingK(a, k, n); document.write(missing); // This code is contributed by suresh07   </script>
14
Time Complexity :O(n), where n is the number of elements in the array. 
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:
C++
Java
Python3
C#
Javascript
// CPP program for above approach#include <iostream>#include <bits/stdc++.h>using namespace std; // Function to find// kth missing numberint missingK(vector<int>& arr, int k){  int n = arr.size();  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 Codeint main(){    vector<int> arr = {2,3,4,7,11};    int k = 5;       // Function Call    cout <<"Missing kth number = "<<                        missingK(arr, k)<<endl;    return 0;}
// Java program for above approachpublic 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.
# Python3 program for above approach # Function to find# kth missing numberdef 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 Codeif __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.
// C# program for above approachusing System;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  static void Main()  {    int[] arr = {2,3,4,7,11};    int k = 5;        // Function Call    Console.WriteLine("Missing kth number = "+ missingK(arr, k));  }} // This code is contributed by divyeshrabadiya07.
<script>// JavaScript program for above approach   // Function to find  // kth missing number  function missingK(arr, k)  {    var n = arr.length;    var l = 0, u = n - 1, mid;       while(l <= u)    {      mid = (l + u)/2;             var 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.    var less = arr[u] - (u + 1);    k -= less;     // Return arr[u] + k    return arr[u] + k;  }   // Driver code    var arr = [2,3,4,7,11];    var k = 5;     // Function Call    document.write("Missing kth number = "+ missingK(arr, k));    // This code is contributed by shivanisinghss2110 </script>
Missing kth number = 9
Time Complexity: O(logn), where n is the number of elements in the array.
Approach 3 (Using Map): We will traverse the array and mark each of the elements as visited in the map and we will also keep track of the min and max element present so that we know the lower and upper bound for the given particular input. Then we start a loop from lower to upper bound and maintain a count variable. As soon we found an element that is not present in the map we increment the count and until the count becomes equal to k.
C++14
Java
Python3
C#
Javascript
#include <iostream>#include <unordered_map>using namespace std; int solve(int arr[] , int k , int n){      unordered_map<int  ,int> umap;      int mins = 99999;      int maxs = -99999;      for(int i=0 ; i<n ; i++)    {          umap[arr[i]] = 1; //mark each element of array in map        if(mins > arr[i])          mins = arr[i];  //keeping track of minimum element        if(maxs < arr[i])          maxs = arr[i]; //keeping track of maximum element i.e. upper bound    }      int counts = 0;      //iterate from lower to upper bound      for(int i=mins ; i<=maxs ; i++)    {          if(umap[i] == 0)          counts++;          if(counts == k)          return i;    }      return -1;}int main() {     int arr[] = {2, 3, 5, 9, 10, 11, 12} ;      int k = 4;      cout << solve(arr , k , 7) ; //(array , k , size of array)    return 0;}
// Java approach // Importing HashMap classimport java.util.HashMap;class GFG {   public static int solve(int arr[] , int k , int n)  {    HashMap<Integer, Integer> umap = new HashMap<Integer, Integer>();    int mins = 99999;    int maxs = -99999;    for(int i = 0; i < n; i++)    {      umap.put(arr[i], 1); // mark each element of array in map      if(mins > arr[i])        mins = arr[i];  // keeping track of minimum element      if(maxs < arr[i])        maxs = arr[i]; // keeping track of maximum element i.e. upper bound    }    int counts = 0;     // iterate from lower to upper bound    for(int i = mins; i <= maxs; i++)    {      if(umap.get(i) == null)        counts++;      if(counts == k)        return i;    }    return -1;  }  public static void main (String[] args)  {    int arr[] = {2, 3, 5, 9, 10, 11, 12} ;    int k = 4;    System.out.println(solve(arr , k , 7)); //(array , k , size of array)  }} // This code is contributed by Shubham Singh
# Python approachdef solve( arr ,  k ,  n):    umap = {}    mins = 99999    maxs = -99999         for i in range(n):        umap[arr[i]] = 1 #mark each element of array in map        if(mins > arr[i]):            mins = arr[i]  #keeping track of minimum element        if(maxs < arr[i]):            maxs = arr[i] #keeping track of maximum element i.e. upper bound    counts = 0         # iterate from lower to upper bound    for i in range(mins, maxs+1):        if(i not in umap):            counts += 1        if(counts == k):            return i    return -1         arr = [2, 3, 5, 9, 10, 11, 12]k = 4print(solve(arr , k , 7))  #(array , k , size of array) # This code is contributed# by Shubham Singh
// C# program for above approachusing System;using System.Collections.Generic;class GFG {         // Function to find    // kth missing number    static int solve(int[] arr, int k, int n)    {                 Dictionary < int, int > umap = new Dictionary < int, int > ();         int mins = 99999;         int maxs = -99999;         for(int i=0 ; i<n ; i++)        {            umap.Add(arr[i], 1); //mark each element of array in map            if(mins > arr[i])              mins = arr[i];  //keeping track of minimum element            if(maxs < arr[i])              maxs = arr[i]; //keeping track of maximum element i.e. upper bound        }        int counts = 0;        //iterate from lower to upper bound        for(int i=mins ; i<=maxs ; i++)        {              if(!umap.ContainsKey(i))                counts++;              if(counts == k)              return i;        }         return -1;    } // Driver codestatic void Main(){    int[] arr = {2, 3, 5, 9, 10, 11, 12};    int k = 4;    int n =  arr.Length;       // Function Call    Console.WriteLine("Missing kth number = "+ solve(arr , k , n)) ;    //(array , k , size of array));}} // This code is contributed by Aarti_Rathi
<script> // JavaScript programfunction solve(arr ,k ,n){    let umap = new Map()    let mins = 99999    let maxs = -99999         for(let i = 0; i < n; i++){        umap.set(arr[i] , 1) //mark each element of array in map        if(mins > arr[i])            mins = arr[i]  //keeping track of minimum element        if(maxs < arr[i])            maxs = arr[i] //keeping track of maximum element i.e. upper bound    }    let counts = 0         // iterate from lower to upper bound    for(let i = mins; i < maxs + 1; i++){        if(!umap.has(i))            counts += 1        if(counts == k)            return i    }    return -1}        // driver code   let arr = [2, 3, 5, 9, 10, 11, 12]let k = 4document.write(solve(arr , k , 7),"</br>")  //(array , k , size of array) // This code is contributed by shinjanpatra </script>
8
manishshaw1
abhishekv
divyeshrabadiya07
divyesh072019
rutvik_56
suresh07
kaivalyamanit
mishravishal2810
RishMeh19
sagartomar9927
shivanisinghss2110
SHUBHAMSINGH10
codewithrathi
shinjanpatra
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array