Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
K’th Smallest Element in Unsorted Array
Next article icon

k-th missing element in an unsorted array

Last Updated : 11 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an unsorted sequence a[], the task is to find the K-th missing contiguous element in the increasing sequence of the array elements i.e. consider the array in sorted order and find the kth missing number. If no k-th missing element is there output -1. 
Note: Only elements exists in the range of minimum and maximum element to be considered. 
Examples: 
 

Input: arr[] = {2, 4, 10, 7}, k = 5 Output: 9 Missing elements in the given array: 3, 5, 6, 8, 9 5th missing is 9.  Input: arr[] = {1, 3, 4}, k = 5 Output: -1


 


Method-1: Sort the array and use the approach used in the k-th missing element in a sorted array.
Method-2: 
 

  1. Insert all the elements in an unordered_set.
  2. Find the minimum and maximum element of the array.

  3. Traverse the elements from minimum to maximum. 
    • Check if current element is present in the set or not.
    • If not then check if this is kth missing by counting the missing elements.
    • Return the current element if this is current missing.


Below is the implementation of the above approach: 
 

C++
// C++ implementation of the above approach #include <bits/stdc++.h> using namespace std;  // Function to find the sum // of minimum of all subarrays int findKth(int arr[], int n, int k) {      unordered_set<int> missing;     int count = 0;      // Insert all the elements in a set     for (int i = 0; i < n; i++)         missing.insert(arr[i]);      // Find the maximum and minimum element     int maxm = *max_element(arr, arr + n);     int minm = *min_element(arr, arr + n);      // Traverse from the minimum to maximum element     for (int i = minm + 1; i < maxm; i++) {         // Check if "i" is missing         if (missing.find(i) == missing.end())             count++;          // Check if it is kth missing         if (count == k)             return i;     }      // If no kth element is missing     return -1; }  // Driver code int main() {     int arr[] = { 2, 10, 9, 4 };     int n = sizeof(arr) / sizeof(arr[0]);     int k = 5;     cout << findKth(arr, n, k);      return 0; } 
Java
// Java implementation of the above approach import java.util.*;  class GFG {      // Function to find the sum     // of minimum of all subarrays     static int findKth(int arr[], int n, int k)      {          HashSet<Integer> missing = new HashSet<>();         int count = 0;          // Insert all the elements in a set         for (int i = 0; i < n; i++)         {             missing.add(arr[i]);         }          // Find the maximum and minimum element         int maxm = Arrays.stream(arr).max().getAsInt();         int minm = Arrays.stream(arr).min().getAsInt();          // Traverse from the minimum to maximum element         for (int i = minm+1; i < maxm; i++)         {             // Check if "i" is missing             if (!missing.contains(i))              {                  count++;             }              // Check if it is kth missing             if (count == k)             {                  return i;             }         }                  // If no kth element is missing         return -1;     }      // Driver code     public static void main(String[] args)      {         int arr[] = {2, 10, 9, 4};         int n = arr.length;         int k = 5;         System.out.println(findKth(arr, n, k));     } }  /* This code contributed by PrinciRaj1992 */ 
Python
# Python3 implementation of the above approach  # Function to find the sum # of minimum of all subarrays def findKth( arr, n, k):      missing = dict()     count = 0      # Insert all the elements in a set     for i in range(n):         missing[arr[i]] = 1      # Find the maximum and minimum element     maxm = max(arr)     minm = min(arr)      # Traverse from the minimum to maximum element     for i in range(minm + 1, maxm):                  # Check if "i" is missing         if (i not in missing.keys()):             count += 1          # Check if it is kth missing         if (count == k):             return i          # If no kth element is missing     return -1  # Driver code arr = [2, 10, 9, 4 ] n = len(arr) k = 5 print(findKth(arr, n, k))  # This code is contributed by Mohit Kumar 
C#
// C# implementation of the above approach  using System; using System.Linq; using System.Collections.Generic;  class GFG  {       // Function to find the sum      // of minimum of all subarrays      static int findKth(int []arr, int n, int k)      {           HashSet<int> missing = new HashSet<int>();          int count = 0;           // Insert all the elements in a set          for (int i = 0; i < n; i++)          {              missing.Add(arr[i]);          }           // Find the maximum and minimum element          int maxm = arr.Max();          int minm = arr.Min();           // Traverse from the minimum to maximum element          for (int i = minm + 1; i < maxm; i++)          {              // Check if "i" is missing              if (!missing.Contains(i))              {                  count++;              }               // Check if it is kth missing              if (count == k)              {                  return i;              }          }                   // If no kth element is missing          return -1;      }       // Driver code      public static void Main(String[] args)      {          int []arr = {2, 10, 9, 4};          int n = arr.Length;          int k = 5;          Console.WriteLine(findKth(arr, n, k));      }  }   // This code has been contributed by 29AjayKumar 
PHP
<?php // PHP implementation of the above approach   // Function to find the sum  // of minimum of all subarrays  function findKth($arr, $n, $k) {      $missing = array();     $count = 0;      // Insert all the elements in a set      for ($i = 0; $i < $n; $i++)         array_push($missing, $arr[$i]);      $missing = array_unique($missing);          // Find the maximum and minimum element      $maxm = max($arr);     $minm = min($arr);      // Traverse from the minimum to     // maximum element      for ($i = $minm + 1; $i < $maxm; $i++)     {         // Check if "i" is missing          if (!in_array($i, $missing, false))             $count += 1;          // Check if it is kth missing          if ($count == $k)              return $i;     }          // If no kth element is missing      return -1; }  // Driver code  $arr = array(2, 10, 9, 4);  $n = sizeof($arr);  $k = 5;  echo findKth($arr, $n, $k);  // This code is contributed by Ryuga ?> 
JavaScript
<script>  // javascript implementation of the above approach  // Function to find the sum // of minimum of all subarrays function findKth(arr, n, k) {      var missing = new Set();     var count = 0;      // Insert all the elements in a set     for (var i = 0; i < n; i++)         missing.add(arr[i]);      // Find the maximum and minimum element     var maxm = arr.reduce((a,b)=>Math.max(a,b));     var minm = arr.reduce((a,b)=>Math.min(a,b));      // Traverse from the minimum to maximum element     for (var i = minm + 1; i < maxm; i++) {         // Check if "i" is missing         if (!missing.has(i))             count++;          // Check if it is kth missing         if (count == k)             return i;     }      // If no kth element is missing     return -1; }  // Driver code var arr = [ 2, 10, 9, 4 ]; var n = arr.length; var k = 5; document.write( findKth(arr, n, k));  // This code is contributed by noob2000. </script>   

Output: 
8

 

Time complexity: O(n) where n is size of input array

Auxiliary Space: O(n)


Next Article
K’th Smallest Element in Unsorted Array

S

Shivam.Pradhan
Improve
Article Tags :
  • Misc
  • Sorting
  • Hash
  • DSA
  • Arrays
  • cpp-unordered_set
Practice Tags :
  • Arrays
  • Hash
  • Misc
  • Sorting

Similar Reads

  • K’th Smallest Element in Unsorted Array
    Given an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples: Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content [Naive
    15+ min read
  • Kth Largest Element in an Array
    Given an integer array arr[] of size n elements and a positive integer K, the task is to return the kth largest element in the given array (not the Kth distinct element). Examples: Input: [1, 23, 12, 9, 30, 2, 50], K = 3Output: 23 Input: [12, 3, 5, 7, 19], K = 2Output: 12 Table of Content [Naive App
    15+ min read
  • Find the Kth occurrence of an element in a sorted Array
    Given a sorted array arr[] of size N, an integer X, and a positive integer K, the task is to find the index of Kth occurrence of X in the given array. Examples: Input: N = 10, arr[] = [1, 2, 3, 3, 4, 5, 5, 5, 5, 5], X = 5, K = 2Output: Starting index of the array is '0' Second occurrence of 5 is at
    15+ min read
  • Count of Missing Numbers in a sorted array
    Given a sorted array arr[], the task is to calculate the number of missing numbers between the first and last element of the sorted array. Examples: Input: arr[] = { 1, 4, 5, 8 } Output: 4 Explanation: The missing integers in the array are {2, 3, 6, 7}. Therefore, the count is 4. Input: arr[] = {5,
    9 min read
  • Find missing element in a sorted array of consecutive numbers
    Given an array arr[] of n distinct integers. Elements are placed sequentially in ascending order with one element missing. The task is to find the missing element.Examples: Input: arr[] = {1, 2, 4, 5, 6, 7, 8, 9} Output: 3Input: arr[] = {-4, -3, -1, 0, 1, 2} Output: -2Input: arr[] = {1, 2, 3, 4} Out
    7 min read
  • Find k smallest elements in an array
    Given an array arr[] and an integer k, the task is to find k smallest elements in the given array. Elements in the output array can be in any order. Examples: Input: arr[] = [1, 23, 12, 9, 30, 2, 50], k = 3Output: [1, 2, 9] Input: arr[] = [11, 5, 12, 9, 44, 17, 2], k = 2Output: [2, 5] Table of Conte
    15 min read
  • Find k largest elements in an array
    Given an array arr[] and an integer k, the task is to find k largest elements in the given array. Elements in the output array should be in decreasing order. Examples: Input: [1, 23, 12, 9, 30, 2, 50], k = 3Output: [50, 30, 23] Input: [11, 5, 12, 9, 44, 17, 2], k = 2Output: [44, 17] Table of Content
    15+ min read
  • Kth Missing Positive Number in a Sorted Array
    Given a sorted array of distinct positive integers arr[] and integer k, the task is to find the kth positive number that is missing from arr[]. Examples : Input: arr[] = [2, 3, 4, 7, 11], k = 5Output: 9Explanation: Missing are 1, 5, 6, 8, 9, 10, ... and 5th missing number is 9. Input: arr[] = [1, 2,
    10 min read
  • Find the only missing number in a sorted array
    You are given a sorted array of N integers from 1 to N with one number missing find the missing number Examples: Input :ar[] = {1, 3, 4, 5}Output : 2Input : ar[] = {1, 2, 3, 4, 5, 7, 8}Output : 6A simple solution is to linearly traverse the given array. Find the point where current element is not on
    9 min read
  • First element occurring k times in an array
    Given an array arr[] of size n, the task is to find the first element that occurs k times. If no element occurs k times, print -1. If multiple elements occur k times, the first one in the array should be the answer. Examples: Input: arr = [1,7,4,3,4,8,7], k=2Output: 7Explanation: Both 7 and 4 occur
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences