VOOZH about

URL: https://www.geeksforgeeks.org/dsa/k-th-missing-element-in-sorted-array/

⇱ Kth Missing Positive Number in a Sorted Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Kth Missing Positive Number in a Sorted Array

Last Updated : 13 Aug, 2025

Given a sorted array of distinct positive integers arr[] and an integer k, find the kth positive integer that is missing from the array.

Examples :

Input: arr[] = [2, 3, 4, 7, 11], k = 5
Output: 9
Explanation: Missing are 1, 5, 6, 8, 9, 10, ... and 5th missing number is 9.

Input: arr[] = [1, 2, 3], k = 2
Output: 5
Explanation: Missing are 4, 5, 6.... and 2nd missing number is 5.

Input: arr[] = [3, 5, 9, 10, 11, 12], k = 2
Output: 2
Explanation: Missing are 1, 2, 4, 6, 7, 8, 13,... and 2nd missing number is 2.

[Naive Approach] Using Hash Set - O(n + k) Time and O(n) Space

The idea is to insert all elements of the array into a set for constant-time lookups. Then, we iterate starting from 1, checking whether each number is missing from the set. For every number not found, we increment a counter. Once we reach the k-th missing number, we return it as the result.


Output
9

[Better Approach] Using Index Comparison - O(n) Time and O(1) Space

The idea is based on the observation that in a perfect sequence without missing numbers, the i-th element should be i + 1. If any number is missing, then arr[i] becomes greater than i + 1, and the number of missing elements before arr[i] is arr[i] - (i + 1).
So, at each index i, we check if the number of missing elements so far is at least k. The first index where arr[i] > k + i indicates that the k-th missing number is before that index and equals k + i.
If no such index is found, it means the k-th missing number lies beyond the last element and is simply k + n.

For example, for [1, 3, 5] and k = 2.

  • For i = 0, we have arr[i] less than 2 + i.
  • For i = 1, we have arr[i] equal to 2 + i.
  • For i = 2, we have arr[i] more than 2 + i. So we return 2 + i which is 4.

Output
9

[Expected Approach] Using Binary Search - O(log n) Time and O(1) Space

In the previous approach, we used linear search to find the first index where arr[i] > (k + i). Since the input array is sorted, once we have found the index i such that arr[i] > (k + i), then for all indices j (j > i), arr[j] will also be greater than (k + j). So, we can optimize the previous approach using binary search to find the index i so that the k-th missing element is k + i.



Output
9
Comment
Article Tags:
Article Tags: