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:
- Initialize two pointers,
leftandright, to the first and last elements of the array, respectively. - Calculate the middle index,
mid, as(left + right) / 2. - Check if the element at the
midindex is present in the array. If it's not, updaterighttomid - 1. This ensures that we're searching for numbers less than or equal to the missing number. - Repeat steps 2-3 until
rightis less than or equal to the Kth missing number. - 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
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;
}