First Missing Positive Integer
Problem
Print the smallest positive integer (1, 2, 3, ...) that is not in the array. Try to solve it in O(n) time.
Constraints
- 1 <= n <= 10^5
Examples
Input
4 3 4 -1 1
Output
2
Solutions
A set gives a simple O(n) time and O(n) space solution. The in-place version puts every value x at index x - 1, so the first wrong place shows the answer. Each swap puts one value in its final place, so the total work is O(n).
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The missing number.
* Approach: Cyclic placement.
* Time : O(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) {
// Step 1: The answer is between 1 and n + 1. So we only care about values in the range 1..n.
int n = a.length;
// Step 2: Put each value x in its own place: index x - 1. Swap until the value at i is wrong for every place or already placed.
for (int i = 0; i < n; i++) {
while (a[i] >= 1 && a[i] <= n && a[a[i] - 1] != a[i]) {
int target = a[i] - 1;
int temporary = a[target];
a[target] = a[i];
a[i] = temporary;
}
}
// Step 3: The first index i where a[i] != i + 1 gives the answer i + 1.
for (int i = 0; i < n; i++) {
if (a[i] != i + 1) {
return i + 1;
}
}
return n + 1;
}
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();
}
System.out.println(solve(a));
}
}
Hints (1)
- What is the biggest possible answer?