Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 – Binary Search for Missing Count
Intuition
Since the array is strictly increasing and sorted, we can efficiently determine how many positive numbers are missing up to any index. By comparing the value at each index with its expected value (index + 1), we can count the missing numbers. Binary search helps us quickly find the smallest index where the count of missing numbers is at least k.
Approach
- For each index i, the number of missing numbers before arr[i] is arr[i] - (i + 1).
- Use binary search to find the smallest index where the missing count is at least k.
- If all missing numbers are before the array ends, the answer is k + the length of the array.
- Otherwise, the answer is arr[left - 1] + (k - missing count at left - 1).
Complexity
- ⏰ Time complexity:
O(log n)
, because we use binary search over the array. - 🧺 Space complexity:
O(1)
, as we use only a few variables for computation.
C++
|
|
Java
|
|
Python
|
|