Kth Missing Positive Number

Find the k-th positive number that is missing from a sorted array, without counting the gaps one by one.

You are given an array arr of positive integers in strictly increasing order, which means each number is bigger than the one before it, and a number k. Of the positive integers 1, 2, 3 and so on, some do not appear in arr. Return the k-th of those missing numbers.

Example 1
Input: arr = [2, 3, 4, 7, 11], k = 5
Output: 9
Explanation: the missing numbers are 1, 5, 6, 8, 9, 10, 12 and so on; the 5th is 9.
Example 2
Input: arr = [1, 2, 3, 4], k = 2
Output: 6
Explanation: nothing is missing up to 4, so the missing numbers are 5, 6, 7 and so on; the 2nd is 6.
Solution

The Idea

Write out the positive numbers 1, 2, 3 and so on, and cross off the ones that appear in the array. In Example 1 that crosses off 2, 3, 4, 7 and 11. The numbers left over, from the left, are 1, 5, 6, 8, 9, 10, then 12 and everything after it. The 5th of them is 9, the answer.

Finding 9 that way means walking through the numbers one at a time. That is fine for k = 5, but k could be a million. So can we tell how many numbers are missing at some point in the array, without counting them one by one?

We can. If nothing were missing, the array would start 1, 2, 3, and the value at index i, counting from 0, would be i + 1. Each missing number below a value pushes that value up by one. So arr[i] - (i + 1) numbers are missing below arr[i]. Look at the picture below.

The numbers 1 to 12 for arr = [2, 3, 4, 7, 11]. Under each value in arr is its index and how many numbers are missing below it: 1, 1, 1, 3 and 6. The missing numbers 1, 5, 6, 8, 9, 10 and 12 are counted 1st to 7th, and the 5th, 9, lies between 7 and 11.

The blue boxes are the values in arr. Take the 7, at index 3. Without gaps it would be 4, and it is 3 higher, so three numbers are missing below it: 1, 5 and 6. Under the 11, at index 4, the count is 6. We want the 5th missing number. Three is too few and six is enough, so the 5th missing number lies between 7 and 11. In the picture it is the orange box, 9.

How do we get from there to 9 without counting? Every number from 1 up to 9 is either missing or in the array. Five of them are missing, up to and including 9 itself, and four are values of the array: 2, 3, 4 and 7. So the answer is 4 + 5 = 9, and that 4 is exactly the index of 11, the first value with at least five numbers missing below it.

So the whole problem comes down to one search: find the first index whose missing count reaches k, and add k to that index.

Solution Approach

Turning that idea into code means settling two things: how to find the first index whose missing count reaches k, and where that search may end.

Finding the first index that reaches k

How do we find that index quickly? The simple way walks the numbers 1, 2, 3 and so on, skips the ones in the array, and stops at the k-th missing one. That takes about n + k steps, where n is the length of the array, which is slow when k is large.

The missing counts help, because they never go down. The array is strictly increasing, so from one index to the next the value grows by at least 1, while i + 1 grows by exactly 1. The count therefore stays the same or grows. In the picture the counts run 1, 1, 1, 3, 6. In such a list, all the counts below k come first and all the others after them. So one look at the middle tells us which half still holds the first count that reaches k.

Keep a range of indexes, from lo to hi, that still holds the index we want. Look at the index in the middle, mid. If its count is less than k, the index we want is to the right of mid, so lo becomes mid + 1. Otherwise mid itself could be the first one, so hi becomes mid. Each look halves the range, and the search stops when lo meets hi. Searching by halving a range like this is called binary search.

In Example 1 the range starts as 0 to 5. It ends at 5, one past the last index, because the answer may lie after the last value. Index 2 has count 1, too few, so lo becomes 3. Index 4 has count 6, so hi becomes 4. Index 3 has count 3, too few, so lo becomes 4 and meets hi. Three looks find index 4, and 4 + 5 = 9.

Where the search may end

What if no value in the array has k numbers missing below it? In Example 2, [1, 2, 3, 4] has nothing missing at all, so the 2nd missing number, 6, comes after the last value. That is why hi starts at arr.length, one past the last index. When every count is below k, lo ends there, at 4, and the answer is 4 + 2 = 6.

An answer before the first value needs nothing special. For [5] and k = 1, index 0 already has four numbers missing below it, so lo stays 0 and the answer is 0 + 1 = 1.

Java Solution

The method findKthPositive works in these steps:

  1. First, set up the range: lo starts at 0 and hi at arr.length, one past the last index, so the search can end after the last value.
  2. While lo is less than hi, take the middle index mid as lo + (hi - lo) / 2. Written this way, the sum lo + hi is never formed, so it cannot grow past the largest int. Then count the numbers missing below arr[mid] into missing, as arr[mid] - (mid + 1).
  3. If missing is less than k, the index we want is to the right, so lo becomes mid + 1. Otherwise hi becomes mid.
  4. When the loop ends, lo is the first index with at least k numbers missing below it, which is also how many values of the array are below the answer. Return lo + k.

The main method runs both examples, an array whose answer comes before its first value, a large k that lands far past the last value, and a small k whose answer falls between two values of the array.

Java
public class KthMissingPositiveNumber {

    public static int findKthPositive(int[] arr, int k) {
        int lo = 0;
        int hi = arr.length;                  // the answer may lie past the last value
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            int missing = arr[mid] - (mid + 1);   // positives missing below arr[mid]
            if (missing < k) {
                lo = mid + 1;                 // fewer than k: the answer is further right
            } else {
                hi = mid;                     // k or more: mid may be the first such index
            }
        }
        return lo + k;                        // lo values are present below the answer
    }

    public static void main(String[] args) {
        System.out.println(findKthPositive(new int[] {2, 3, 4, 7, 11}, 5));
        System.out.println(findKthPositive(new int[] {1, 2, 3, 4}, 2));
        System.out.println(findKthPositive(new int[] {5}, 1));
        System.out.println(findKthPositive(new int[] {2, 3, 4, 7, 11}, 1000));
        System.out.println(findKthPositive(new int[] {2, 3, 4, 7, 11}, 3));
    }
}

Running it prints:

Output
9
6
1
1005
6

Look at the second line, 6, from [1, 2, 3, 4] with k = 2. Every count there is 0, so lo ends at 4, past the last index, and 4 + 2 gives 6. The fourth line, 1005, ends the same way: all five values of [2, 3, 4, 7, 11] have fewer than 1,000 numbers missing below them, so the answer is 5 + 1000.

The third line, 1, comes from [5] with k = 1, where lo never moves. The last line asks Example 1 for its 3rd missing number. The first value with three numbers missing below it is 7, at index 3, and 3 + 3 gives 6, which sits between 4 and 7.

Starting with hi = arr.length - 1, the usual last index, breaks the second and fourth lines. With that one change the program prints 5 instead of 6 and 1004 instead of 1005, because lo can then never move past the last index.

Complexity

The only work is the binary search, and it never looks at the missing numbers one by one.

  • Time: O(log n), where n is the length of the array. The range from lo to hi starts with n + 1 positions, and each pass of the loop halves it. The size of k does not matter, unlike walking the numbers one at a time, which takes about n + k steps.
  • Space: O(1). The search keeps only lo, hi, mid and missing, and the array is only read.

Searching for the first index where a condition becomes true is the pattern shown in Binary Search Basics.