Practice › Arrays
First Missing Positive
Hard · Arrays · Asked at Amazon, Google, Microsoft, Meta, Samsung
Print the smallest positive integer that does not appear in the array. Aim for O(n) time and O(1) extra space.
Input
First line: n. Second line: n space-separated integers.
Output
The smallest missing positive integer.
Constraints
- 1 ≤ n ≤ 10^5
- −2^31 ≤ a[i] ≤ 2^31 − 1
The answer is in 1 … n + 1. Place every value v in 1 … n at index v − 1 by swapping (cyclic sort). Then the first index i with a[i] ≠ i + 1 gives the answer i + 1; if all match, it is n + 1.
Example 1
Input
3 1 2 0
Output
3
Example 2
Input
4 3 4 -1 1
Output
2
Example 3
Input
5 7 8 9 11 12
Output
1
Hints
- With n numbers, the answer is always between 1 and n + 1.
- Try to put every value v (1 ≤ v ≤ n) at index v − 1.
- After that, the first index i holding something other than i + 1 gives the answer.
Approach
Cyclic sort: for each i, while a[i] is in 1 … n and a[a[i] − 1] ≠ a[i], swap a[i] into its home position. Every swap puts at least one value home for good, so there are at most n swaps in total. Then scan for the first i with a[i] ≠ i + 1 and print i + 1; if all match, print n + 1. Values outside 1 … n (negatives, zero, large numbers, duplicates) are simply left where they are.
Complexity: O(n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<long long> a(n);
for (auto &x : a) cin >> x;
for (int i = 0; i < n; i++)
while (a[i] >= 1 && a[i] <= n && a[a[i] - 1] != a[i]) swap(a[i], a[a[i] - 1]);
for (int i = 0; i < n; i++)
if (a[i] != i + 1) {
cout << i + 1 << "\n";
return 0;
}
cout << n + 1 << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = data[1 : 1 + n]
for i in range(n):
while 1 <= a[i] <= n and a[a[i] - 1] != a[i]:
j = a[i] - 1
a[i], a[j] = a[j], a[i]
answer = n + 1
for i in range(n):
if a[i] != i + 1:
answer = i + 1
break
print(answer)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
long[] a = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
for (int i = 0; i < n; i++)
while (a[i] >= 1 && a[i] <= n && a[(int) a[i] - 1] != a[i]) {
int j = (int) a[i] - 1;
long t = a[i];
a[i] = a[j];
a[j] = t;
}
for (int i = 0; i < n; i++)
if (a[i] != i + 1) {
System.out.println(i + 1);
return;
}
System.out.println(n + 1);
}
}