The 30 second answer
The answer is always between one and n plus one, so only values in that range matter. I do a cyclic sort, swapping each value v in one to n into index v minus one until every slot holds its own number or a value I can ignore. Then the first index i where nums of i is not i plus one gives the answer, otherwise n plus one. Linear time, constant space.
Problem Given an unsorted integer array, return the smallest positive integer that doesn't appear, in O(n) time and O(1) extra space. Original: LeetCode 41: First Missing Positive.
Understanding the prompt Negatives, zeros, duplicates and values larger than n can all appear. The time and space limits rule out sorting and sets.
Pattern recognition The answer is bounded to 1..n+1, and only O(1) space is allowed. That means using the array itself as the hash table: cyclic sort.
Brute force A HashSet, then test 1, 2, 3 and so on: O(n) time but O(n) space. Sorting: O(n log n).
Optimal For each i, while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i], swap nums[i] into its home. Then scan for the first nums[i] != i + 1.
Alternatives Sign marking: first replace out-of-range values with n+1, then flip the sign at index |v| − 1 for each in-range v.
Java solution
public class FirstMissingPositive {
static int firstMissingPositive(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
while (nums[i] >= 1 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
int home = nums[i] - 1;
int tmp = nums[home];
nums[home] = nums[i];
nums[i] = tmp;
}
}
for (int i = 0; i < n; i++) {
if (nums[i] != i + 1) return i + 1;
}
return n + 1;
}
public static void main(String[] args) {
System.out.println(firstMissingPositive(new int[] {1, 2, 0})); // 3
System.out.println(firstMissingPositive(new int[] {3, 4, -1, 1})); // 2
System.out.println(firstMissingPositive(new int[] {7, 8, 9, 11, 12})); // 1
System.out.println(firstMissingPositive(new int[] {1, 1})); // 2
}
}Complexity O(n) time, because each swap puts at least one value in its final home, so there are at most n swaps in total. O(1) extra space.
Edge cases
- Duplicates: the
nums[home] != nums[i]check prevents an infinite loop. - All values out of range returns 1.
- 1..n all present returns n+1.
Follow-ups
- Prove the bound on swaps.
- Do it without modifying the input: not possible in O(1) space. Say so and offer the O(n)-space set version.
Tests [1,2,0] returns 3. [3,4,-1,1] returns 2. [7,8,9,11,12] returns 1. [1,1] returns 2.
How to say it in the interview "The answer is between 1 and n+1, so I treat the array as its own hash table. I swap every in-range value into index value−1, guarding against duplicates. The first slot that doesn't hold its own number is the answer. Every swap fixes one value, so it's O(n) time with O(1) space."
Sources (1)
- LeetCode 41: First Missing Positiveleetcode.com