Kth - missing positive number


kth-missing-positive-number


Problem Statement

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

Your task is to return the k-th positive integer that is missing from the array.


Examples


Constraints


Intuition

In a perfect sequence of positive integers [1, 2, 3, ...], the i-th index would have the value i + 1.

But since elements are missing in arr, the number of missing elements before index i is:

missing = arr[i] - (i + 1)

We want to find the first position i such that the number of missing integers before it is at least k.

This makes it suitable for binary search.


  1. Initialize search boundaries: start = 0, end = arr.length - 1

  2. While start <= end:

    • Compute mid = start + (end - start) / 2

    • Calculate how many numbers are missing before mid:

      missing = arr[mid] - (mid + 1)
      
    • If missing < k, move right → start = mid + 1

    • Else, move left → end = mid - 1

  3. After the loop ends, the answer is:

    start + k
    

Java Code

class Solution {
    public int findKthPositive(int[] arr, int k) {
        int start = 0;
        int end = arr.length - 1;

        while (start <= end) {
            int mid = start + (end - start) / 2;

            int missing = arr[mid] - (mid + 1);
            if (missing < k) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }

        return start + k;
    }
}

Time and Space Complexity


Dry Run

Input:

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

Iterations:

Loop ends: start = 4, so answer = 4 + 5 = 9

Output: 9


Conclusion

This problem showcases a smart application of binary search over virtual properties of a sequence (in this case, the number of missing elements). The trick lies in calculating how many numbers are missing up to any given index and narrowing the search accordingly.

This technique is powerful for problems involving gaps or differences in expected versus actual sequences.