{x}
blog image

Kth Missing Positive Number

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

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

 

Example 1:

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.

Example 2:

Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.

 

Constraints:

  • 1 <= arr.length <= 1000
  • 1 <= arr[i] <= 1000
  • 1 <= k <= 1000
  • arr[i] < arr[j] for 1 <= i < j <= arr.length

 

Follow up:

Could you solve this problem in less than O(n) complexity?

Solution Explanation

This problem asks to find the k-th missing positive integer in a sorted array. The solution leverages binary search for efficiency.

Approach:

The core idea is to efficiently determine the number of missing positive integers up to a certain point in the array. We use binary search to find the index left such that the number of missing integers before arr[left] is less than k, but the number of missing integers before arr[left+1] (or the end of the array) is greater than or equal to k.

The number of missing integers before arr[i] is simply arr[i] - i - 1. This is because the i-th element should ideally be i + 1 if there were no missing numbers. The difference gives us the count of missing numbers.

Once we find the index left, we know that the k-th missing number lies after arr[left-1] (or at the beginning if left is 0). We calculate the number of missing integers up to arr[left-1], and the remaining k minus this count gives us how many more positions to move forward from arr[left-1] to find the k-th missing number.

Time Complexity: O(log n), where n is the length of the array. This is due to the binary search.

Space Complexity: O(1). The solution uses a constant amount of extra space.

Code Explanation (Python):

class Solution:
    def findKthPositive(self, arr: List[int], k: int) -> int:
        if arr[0] > k:  # Handle the case where k is smaller than the first element
            return k
 
        left, right = 0, len(arr)  # Binary search range
        while left < right:
            mid = (left + right) >> 1  # Bitwise right shift for efficient division by 2
            if arr[mid] - mid - 1 >= k:  # Check if enough missing numbers exist before arr[mid]
                right = mid  # Narrow down the search space
            else:
                left = mid + 1
 
        # Calculate the k-th missing number based on the index found by binary search
        return arr[left - 1] + k - (arr[left - 1] - (left - 1) - 1)
 

The other languages (Java, C++, Go) follow the same logic and algorithm, just with syntax specific to their respective languages. The core binary search and missing number calculation remain consistent.