Kth Missing Positive Number

Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.

Find the kth positive integer that is missing from this array.

Example

Input: arr=[2,3,4,7,11], k=5

Output: 9

Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.


Solution

Python solution

def binary_search(arr: List[int], k: int) -> int: if arr[0] > k: return k

l = 0
r = len(arr) - 1
while l < r:
    mid = (l + r) // 2
    x = arr[mid] if mid < len(arr) else 10**9
    if x - mid - 1 >= k:
        r = mid
    else:
        l = mid + 1

return k - (arr[l - 1] - (l - 1) - 1) + arr[l - 1]

Java Solution

public int binarySearch(int[] arr) { if (arr[0] > k) { return k; }

int l = 0;
int r = arr.length - 1;
while (l < r) {
    int mid = (l + r) / 2;
    int x = mid < arr.length ? arr[mid] : Integer.MAX_VALUE;
    if (x - mid - 1 >= k) {
        r = mid;
    } else {
        l = mid + 1;
    }
}

return k - (arr[l - 1] - (l - 1) - 1) + arr[l - 1];

}

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator
Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

Which algorithm is best for finding the shortest distance between two points in an unweighted graph?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!


Load More