Kth Missing Positive Number (LeetCode 1539): Solution and Explanation
You get a strictly increasing array of positive integers and a number k. Counting the positive integers that are not in the array, starting from 1, return the kth one.
Watch it run step by step
Try your own input and write the code →Intuition
The simplest approach walks the positive integers 1, 2, 3 and so on, checking each against the array with a pointer and counting the ones that are absent until the count reaches k. That is O(n + k), which is fine for the given limits but ignores that the array is sorted, and the follow-up asks for something faster than linear.
The useful observation is that you can compute how many numbers are missing before any position in constant time. If nothing were missing, arr[i] would equal i + 1. Every missing number before it pushes it one higher, so the number of missing positives smaller than arr[i] is exactly arr[i] - (i + 1). For arr = [2, 3, 4, 7, 11], that count is 1, 1, 1, 3, 6. Because the array strictly increases, this count never decreases as i grows, so it is a sorted sequence you can binary search.
Search for the first index left where the missing count is at least k. Then exactly left array elements are smaller than the answer, and the answer is the kth missing number, so it must be k + left: you count k missing numbers and skip over the left present ones mixed in among them. This also covers the edges. If even the last element has fewer than k missing numbers below it, left becomes n and the answer lies past the end of the array; if k is smaller than arr[0], left is 0 and the answer is just k.
Approach: Binary search on the missing count
- Set
left = 0andright = len(arr) - 1. - While
left <= right, takemid = (left + right) // 2and computemissing = arr[mid] - (mid + 1), the count of absent positives belowarr[mid]. - If
missing < k, the answer lies to the right ofarr[mid], so setleft = mid + 1. - Otherwise the answer is before
arr[mid], so setright = mid - 1. - When the loop ends,
leftis the number of array elements smaller than the answer. Returnleft + k.
Step-by-step example
arr = [2, 3, 4, 7, 11], k = 5
- Start with
left = 0,right = 4.mid = 2,arr[2] = 4, andmissing = 4 - 3 = 1, which is less than 5, soleft = 3. mid = 3,arr[3] = 7, andmissing = 7 - 4 = 3, still less than 5, soleft = 4.mid = 4,arr[4] = 11, andmissing = 11 - 5 = 6, which is at least 5, soright = 3.- Now
left > rightand the loop ends withleft = 4. - The function returns 4 + 5 = 9. The missing numbers are 1, 5, 6, 8, 9, so the fifth is indeed 9.
Code: Python, Java, C++
1class Solution:
2 def findKthPositive(self, arr: List[int], k: int) -> int:
3 left, right = 0, len(arr) - 1
4 while left <= right:
5 mid = (left + right) // 2
6 # Number of missing positives before arr[mid]
7 missing = arr[mid] - (mid + 1)
8 if missing < k:
9 left = mid + 1
10 else:
11 right = mid - 1
12 # left is the first index where missing >= k
13 # Answer = k + left (since left elements are present before answer)
14 return left + k1class Solution {
2 public int findKthPositive(int[] arr, int k) {
3 int left = 0, right = arr.length - 1;
4 while (left <= right) {
5 int mid = left + (right - left) / 2;
6 // Number of missing positives before arr[mid]
7 int missing = arr[mid] - (mid + 1);
8 if (missing < k) {
9 left = mid + 1;
10 } else {
11 right = mid - 1;
12 }
13 }
14 // left is the first index where missing >= k
15 // Answer = k + left (since left elements are present before answer)
16 return left + k;
17 }
18}1class Solution {
2public:
3 int findKthPositive(vector<int>& arr, int k) {
4 int left = 0, right = arr.size() - 1;
5 while (left <= right) {
6 int mid = left + (right - left) / 2;
7 // Number of missing positives before arr[mid]
8 int missing = arr[mid] - (mid + 1);
9 if (missing < k) {
10 left = mid + 1;
11 } else {
12 right = mid - 1;
13 }
14 }
15 // left is the first index where missing >= k
16 // Answer = k + left (since left elements are present before answer)
17 return left + k;
18 }
19};Time and space complexity
O(log n)
Each iteration halves the search range, and computing the missing count at mid is constant time.
O(1)
Only the two bounds and the midpoint are stored.
Other approaches
Linear scan with a counter (time O(n), space O(1))
Walk the array and, for each element, check whether arr[i] - i - 1 >= k. The first index where that holds gives the answer as i + k; if none does, the answer is n + k. It is simple and runs in O(n), which is fine for small arrays.
Count up from 1 (time O(n + k), space O(1))
Iterate candidate numbers from 1 upward with a pointer into the array, decrementing k for each candidate not present. It is the most literal reading of the problem but can do up to n + k iterations.
Common mistakes
- Returning
arr[left] + somethinginstead ofleft + k. Whenleftequals n,arr[left]is out of bounds, and the formula withlefthandles that case directly. - Computing the missing count as
arr[mid] - midwithout the extra minus one. With zero-based indices the expected value at positionmidismid + 1. - Using
missing <= kin the comparison. You want the first index where the count reachesk, so the boundary test must bemissing < kto move right. - Assuming the answer is always inside the array's range. For
arr = [1, 2, 3, 4]andk = 2, the answer is 6, beyond the last element.
Frequently asked questions
Why is the answer left + k?
After the search, exactly left array elements are smaller than the answer. The answer is the kth number not in the array, so its value is k missing numbers plus the left present numbers that come before it.
How do you count missing numbers before arr[i]?
With no gaps, arr[i] would equal i + 1. Each missing number shifts it up by one, so the count of missing positives below it is arr[i] - i - 1.
Can Kth Missing Positive Number be solved in less than O(n)?
Yes. Because the missing count is non-decreasing along a strictly increasing array, binary search finds the boundary in O(log n) time.