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.
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.
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.
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.