59 lines
2.2 KiB
Java
59 lines
2.2 KiB
Java
package com.dsa.binarysearch;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.FileReader;
|
|
import java.io.IOException;
|
|
import java.util.Arrays;
|
|
|
|
public class KthMissingNumber {
|
|
public static void main(String[] args) {
|
|
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
|
|
int n = Integer.parseInt(reader.readLine().trim());
|
|
String[] numbers = reader.readLine().trim().split(",");
|
|
int k = Integer.parseInt(reader.readLine().trim());
|
|
int[] arr = new int[n];
|
|
for (int i = 0; i < n; i++) {
|
|
arr[i] = Integer.parseInt(numbers[i].trim());
|
|
}
|
|
KthMissingNumber solution = new KthMissingNumber();
|
|
System.out.println("Input Array: " + Arrays.toString(arr) + ", K: " + k);
|
|
System.out.println("Kth Missing Number: " + solution.getMissingNumber(arr, k));
|
|
} catch (IOException e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
public int getMissingNumber(int[] nums, int k) {
|
|
int left = 0;
|
|
int right = nums.length - 1;
|
|
|
|
while (left <= right) {
|
|
int mid = (left + right) / 2;
|
|
int missingCount = nums[mid] - mid - 1;
|
|
if (missingCount < k) {
|
|
left = mid + 1;
|
|
} else {
|
|
right = mid - 1;
|
|
}
|
|
}
|
|
/*
|
|
After the loop, the left pointer indicates the position where the kth missing number would fit.
|
|
Eg: 2, 3, 4, 7, 11 and k = 5
|
|
Missing numbers are 1, 5, 6, 8, 9, 10, ...
|
|
At the end of the loop, left = 4 (pointing to 11)
|
|
and right = 3 (pointing to 7)
|
|
The missing number would be between 7 and 11.
|
|
So to get the 5th missing number, we calculate it as:
|
|
nums[high] + k - missingCount at high
|
|
missingCount at index 3 (value 7) = 7 - 3 - 1 = 3
|
|
So, 7 + 5 - 3 = 9
|
|
we can rewrite nums[high] + k - (nums[high] - high - 1)
|
|
which simplifies to nums[high] + k - nums[high] + high + 1
|
|
which further simplifies to high + k + 1
|
|
Since high = left - 1, we can rewrite it as:
|
|
(left - 1) + k + 1 = left + k
|
|
*/
|
|
return left + k;
|
|
}
|
|
}
|