k-th Missing Positive Number
Problem
The array is sorted, has different positive numbers and grows strictly. Print the k-th positive whole number that is not in the array (counting 1, 2, 3, ...). For 2 3 4 7 11 the missing numbers are 1, 5, 6, 8, 9, 10, 12, ...
Constraints
- 1 <= n <= 10^5
- 1 <= a[i] <= 10^9
- 1 <= k <= 10^9
Examples
Input
5 2 3 4 7 11 5
Output
9
Solutions
The count of missing numbers before position i is a[i] - (i + 1). It never decreases, so binary search finds the first position with at least k missing numbers. The answer is then low + k. This takes O(log n).
/*
* Problem : k-th missing number.
* Input : n, the array, then k.
* Output : The number.
* Approach: Binary search on the missing count.
* Time : O(log n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int solve(int[] a, int k) {
// Step 1: Before index i there are a[i] - (i + 1) missing numbers. This count never goes down, so we can use binary search.
int low = 0;
int high = a.length;
while (low < high) {
int middle = low + (high - low) / 2;
// Step 2: If fewer than k numbers are missing before a[middle], the answer is to the right.
if (a[middle] - (middle + 1) < k) {
low = middle + 1;
} else {
high = middle;
}
}
// Step 3: "low" numbers of the array are smaller than the answer, so the answer is low + k.
return low + k;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
int k = scanner.nextInt();
System.out.println(solve(a, k));
}
}
Hints (2)
- How many numbers are missing before a[0] = 5?
- Why is the answer low + k?