The problem. Given an array arr of positive integers sorted in strictly increasing order, and an integer k, return the k-th positive integer missing from the array.
arr = [2, 3, 4, 7, 11], k = 5 -> 9 (missing 1, 5, 6, 8, 9, ...)
arr = [1, 2, 3, 4], k = 2 -> 6 (missing 5, 6, ...)
arr = [5, 6, 7], k = 3 -> 3 (missing 1, 2, 3, ...)If nothing were missing, arr[i] would be i + 1. So `arr[i] - (i + 1)` numbers are missing below arr[i]. That count never decreases as i grows — a sorted sequence hiding inside the array. Binary search it for the first index i with at least k missing. Then the answer sits after the first i values of the array and after k missing numbers, so it's exactly `i + k`. (If every value has fewer than k missing, i is the array's length and the formula still works.)
Start with the answer k, as if nothing were in the array. Each array value at or below the answer takes up a spot, pushing the answer one further.
function findKthPositive(arr, k) { for (const value of arr) { if (value <= k) k++; // a value at or below the answer pushes it one further else break; } return k;}Time O(n), space O(1). Short and clever — and the follow-up asks for better than O(n).
Find the first index with at least k numbers missing before it; the answer is that index plus k.
function findKthPositive(arr, k) { let low = 0; let high = arr.length; while (low < high) { const mid = low + Math.floor((high - low) / 2); if (arr[mid] - (mid + 1) < k) low = mid + 1; // fewer than k missing before arr[mid] else high = mid; } return low + k; // low array values and k missing numbers come first}Time O(log n), space O(1). The search isn't over the values or the answers but over a derived sorted sequence — the missing counts — computed on the fly at each mid.
[1, 2, 3, 4], k = 2: the answer is past the end, 6.[5, 6, 7], k = 3: the answer 3 comes before arr[0].[1], k = 1 gives 2; [2], k = 1 gives 1.