First Missing Positive

Find the smallest positive number missing from an unsorted array, by rearranging the array in place.

You are given an array of integers nums in no particular order. It may hold zeros, negative numbers, repeats and very large values. Return the smallest positive integer, counting 1, 2, 3 and so on, that does not appear in the array. The solution should take time in proportion to the length of the array and use only a fixed amount of memory besides the array itself.

Example 1
Input: nums = [1, 2, 0]
Output: 3
Example 2
Input: nums = [3, 4, -1, 1]
Output: 2
Example 3
Input: nums = [7, 8, 9, 11, 12]
Output: 1
Solution

The Idea

Think of a row of mailboxes numbered 1, 2, 3 and so on, and a pile of letters, each marked with a number. Put every letter into the box with its number. The first empty box then shows the smallest number that no letter carries.

Take Example 2, [3, 4, -1, 1], as four letters. The 3 goes into box 3, the 4 into box 4 and the 1 into box 1. Box 2 gets nothing, so the answer is 2. The -1 has no box at all, since no box has a number below 1.

That raises a question: how many boxes do we need? A letter marked 7 would want box 7. Here is the key observation. For the answer to be bigger than some number k, the array must contain every number from 1 to k. An array of n numbers can contain at most 1 to n, so the answer is never more than n + 1.

So n boxes are enough, and any value below 1 or above n can never decide the answer. Example 3, [7, 8, 9, 11, 12], has five numbers, all above 5. None of them has a box, box 1 stays empty, and the answer is 1.

The boxes do not need extra memory either: the array itself can be the row. Index 0 is the slot for the value 1, index 1 the slot for 2, and in general index v - 1 is the slot for the value v. Look at the picture below.

Before: the array 3, 4, -1, 1 at indexes 0 to 3. Blue arrows carry 3, 4 and 1 to their slots, and a dashed arrow takes -1 to the slot nobody claimed. After: 1, -1, 3, 4. The slot for 2 holds -1, so the answer is 2.

The top row is Example 2 as given. Each blue arrow carries a value to its slot: the 3 from index 0 to the slot for 3, the 4 to the slot for 4, and the 1 to the slot for 1. The grey -1 has no slot, and the dashed arrow shows it ending up in the one slot nobody claimed. Reading the bottom row from the left, the slot for 2 is the first that does not hold its own value, so the answer is 2.

So the array can be rearranged in place, with every value from 1 to n in its own slot and everything else in the slots left over. The first slot that does not hold its value gives the answer.

Solution Approach

Turning that idea into code means settling three things: how to move each value into its slot without a second array, when to stop moving values, and how to read the answer from the slots.

Moving values into their slots

Why move values at all? The simplest way is to check 1, then 2, then 3, scanning the whole array for each. With n numbers that can take n + 1 scans of n numbers each, about a million steps for 1,000 numbers. A HashSet of the numbers makes each check a single step, but the set needs room for up to n numbers. Sorting the array first also works, but sorting takes more than one pass over the array.

Placing values in their slots avoids both costs. To get a value into its slot, swap it with whatever is there. In Example 2, index 0 holds 3, whose slot is index 2. The swap puts 3 in place and brings -1 to index 0: [-1, 4, 3, 1]. The -1 has no slot, so index 0 is done.

At index 1, the 4 swaps into index 3 and brings back 1: [-1, 1, 3, 4]. That 1 has a slot too, index 0, and a second swap gives [1, -1, 3, 4], the bottom row of the picture. A value that comes back from a swap may need a swap of its own, so the work at one index is a loop, not a single swap. Sorting by swapping each value straight to the position its value names is called cyclic sort.

When to stop swapping

When does the loop at one index end? When the value there is below 1 or above n, since it has no slot. It also ends when the value's slot already holds that same value. Without this second check, a repeated value would keep swapping with its own copy.

Take [1, 1]. At index 1 sits a 1, whose slot, index 0, already holds 1. Swapping them would exchange 1 for 1 and change nothing, so the loop stops there, and the extra 1 stays in the slot for 2.

Reading the answer

Once every value is in place, where is the answer? Walk the slots from index 0. The first index i that does not hold i + 1 gives the answer, i + 1. If every slot holds its own value, the array holds exactly 1 to n, and the answer is n + 1.

Java Solution

The method firstMissingPositive works in these steps:

  1. First, store the length of the array in n. The values from 1 to n are the ones with a slot.
  2. A for loop moves i along the array, from index 0 to the end.
  3. Inside it, a while loop keeps placing the value at nums[i]. It runs while that value is between 1 and n and its slot does not already hold it. Each round, target is the value's slot, nums[i] - 1, and tmp keeps the value found there. The two values swap, and the loop looks at the value that came back.
  4. A second for loop walks the slots again and returns i + 1 at the first index i where nums[i] is not i + 1.
  5. If every slot holds its own value, return n + 1.

The main method runs the three examples, then [1, 1] with its repeat, [4, 3, 2, 1] with every value from 1 to 4, and an empty array.

Java
public class FirstMissingPositive {

    public static int firstMissingPositive(int[] nums) {
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            // keep placing until slot i holds a value that stays
            while (nums[i] >= 1 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
                int target = nums[i] - 1;     // the slot where this value belongs
                int tmp = nums[target];
                nums[target] = nums[i];
                nums[i] = tmp;                // the value that was there gets placed next
            }
        }
        for (int i = 0; i < n; i++) {
            if (nums[i] != i + 1) {
                return i + 1;                 // the first slot without its value
            }
        }
        return n + 1;                         // 1..n are all present
    }

    public static void main(String[] args) {
        System.out.println(firstMissingPositive(new int[] {1, 2, 0}));
        System.out.println(firstMissingPositive(new int[] {3, 4, -1, 1}));
        System.out.println(firstMissingPositive(new int[] {7, 8, 9, 11, 12}));
        System.out.println(firstMissingPositive(new int[] {1, 1}));
        System.out.println(firstMissingPositive(new int[] {4, 3, 2, 1}));
        System.out.println(firstMissingPositive(new int[] {}));
    }
}

Running it prints:

Output
3
2
1
2
5
1

The first line, 3, comes from [1, 2, 0], where the 0 ends up in the slot for 3. The second line, 2, is Example 2 after the swaps in the picture. Look at the third line, the 1 from [7, 8, 9, 11, 12]: every value there is above 5, so the while loop never swaps, and index 0 does not hold 1.

The fourth line, 2, comes from [1, 1], and it depends on how the while loop tests the slot. The code checks the slot's content, nums[nums[i] - 1] != nums[i]. A test of nums[i] != i + 1 looks like it means the same, but it does not. At index 1 the value 1 is never 2, so that version swaps 1 with 1 forever. Run on [1, 1], it was still swapping after a million swaps.

The fifth line, 5, is the case where nothing is missing: [4, 3, 2, 1] ends up as 1 to 4 in order, the second loop finds no gap, and the method returns n + 1. The last line is the empty array. Both loops are skipped, and n + 1 is 1.

The original implementation, FirstMissingPositive.java, is on GitHub.

Complexity

The work is one pass that swaps values into their slots, plus one more pass to read the slots.

  • Time: O(n), for an array of n numbers, even though the while loop inside the for loop looks like it could cost n² steps. Every swap puts one value into its slot for good, and a value in its own slot is never moved again. So all the while loops together make at most n swaps, and the second pass adds n more steps.
  • Space: O(1). The array is rearranged in place, and the method keeps only n, i, target and tmp. The price is that the caller's array comes back reordered, so pass a copy if the original order matters.

Marking slots by flipping a value's sign, instead of swapping, is the idea behind Find All Numbers Disappeared in an Array.