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
Example 1
Output: 3
Example 2
Output: 2
Example 3
Output: 1
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]
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]
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.
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
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]
At index 1, the 4 swaps into index 3 and brings back 1: [-1, 1, 3, 4][1, -1, 3, 4]
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]
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
- First, store the length of the array in
. The values from 1 ton are the ones with a slot.n - A
loop movesfor along the array, from index 0 to the end.i - Inside it, a
loop keeps placing the value atwhile . It runs while that value is between 1 andnums[i] and its slot does not already hold it. Each round,n is the value's slot,target , andnums[i] - 1 keeps the value found there. The two values swap, and the loop looks at the value that came back.tmp - A second
loop walks the slots again and returnsfor at the first indexi + 1 wherei is notnums[i] .i + 1 - If every slot holds its own value, return
.n + 1
The main[1, 1][4, 3, 2, 1]
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:
3
2
1
2
5
1
The first line, 3, comes from [1, 2, 0][7, 8, 9, 11, 12]while
The fourth line, 2, comes from [1, 1]whilenums[nums[i] - 1] != nums[i]nums[i] != i + 1[1, 1]
The fifth line, 5, is the case where nothing is missing: [4, 3, 2, 1]n + 1n + 1
The original implementation,
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
loop inside thewhile 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 thefor loops together make at most n swaps, and the second pass adds n more steps.while - Space: O(1). The array is rearranged in place, and the method keeps only
,n ,i andtarget . The price is that the caller's array comes back reordered, so pass a copy if the original order matters.tmp
Marking slots by flipping a value's sign, instead of swapping, is the idea behind