This approach involves iterating through the array and maintaining a counter for missing positive integers. We start with the first positive number, which is 1, and determine if it is missing by comparing it to the current element in the array. If the number is missing, we decrement our k value. When k reaches zero, we have found our k-th missing number.
Time Complexity: O(n + k), where n is the length of the array. Space Complexity: O(1), as we are using constant extra space.
1def findKthPositive(arr, k):
2 missing_count = 0
3 current = 1
4 i = 0
5 while missing_count < k:
6 if i < len(arr) and arr[i] == current:
7 i += 1
8 else:
9 missing_count += 1
10 if missing_count == k:
11 return current
12 current += 1
13 return -1 # this line is never reached
14
15arr = [2, 3, 4, 7, 11]
16k = 5
17print(findKthPositive(arr, k))
This Python solution is straightforward and utilizes a while loop to track missing numbers. The logic is similar to that in C/C++/Java implementations, making it easy to follow along.
By using binary search, a more efficient solution can be developed that reduces unnecessary checks. The key observation is that the number of missing integers before arr[i] can be calculated as arr[i] - (i + 1), which helps in deducing the position of the k-th missing number without iterating through every integer.
Time Complexity: O(log n), Space Complexity: O(1).
1public class 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 if (arr[mid] - (mid + 1) < k) {
7 left = mid + 1;
8 } else {
9 right = mid - 1;
10 }
11 }
12 return left + k;
13 }
14 public static void Main(string[] args) {
15 int[] arr = {2, 3, 4, 7, 11};
16 Solution solution = new Solution();
17 Console.WriteLine(solution.FindKthPositive(arr, 5));
18 }
19}
The C# version uses binary search to determine the location of the k-th missing integer by calculating the difference between the actual values and the indices.