874780. Kth Missing Positive Number in a Sorted Array

Medium

Kth Missing Positive Number in a Sorted Array

Slug: kth-missing-positive-number-in-a-sorted-array

Difficulty: Medium

Id: 874780

Topic Tags: Binary Search, Arrays

Company Tags: None

Summary

Given a sorted array of positive integers, find the Kth missing number. For example, if the input is [1,2,3,4,5] and K = 2, the output should be 3 because there are two missing numbers (2 and 4) in the range [1,5]. The problem requires using a binary search approach to solve it efficiently.

Detailed Explanation

The problem can be solved by performing a binary search on the given array. We start with the first element of the array and keep searching for the next positive number until we find the Kth missing number. Here's a step-by-step breakdown:

  1. Initialize two pointers, left and right, to the first and last elements of the array, respectively.
  2. Calculate the middle index, mid, as (left + right) / 2.
  3. Check if the element at the mid index is present in the array. If it's not, update right to mid - 1. This ensures that we're searching for numbers less than or equal to the missing number.
  4. Repeat steps 2-3 until right is less than or equal to the Kth missing number.
  5. The Kth missing number is the smallest positive integer greater than right.

Time complexity: O(log(n)) where n is the size of the array. Space complexity: O(1) as we're only using a few extra variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int findKthMissingNumber(int[] nums, int k) {
    int left = 0;
    int right = nums.length - 1;

    while (right - left > 1) {
        int mid = left + (right - left) / 2;

        if (nums[mid] == mid + 1) {
            left = mid;
        } else {
            right = mid;
        }
    }

    for (int i = left; i < nums.length; i++) {
        if (i + 1 != nums[i]) {
            k--;
        }
        if (k == 0) {
            return i + 1;
        }
    }

    return -1;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.