# LeetCode – First Missing Positive (Java)

Given an unsorted integer array, find the first missing positive integer. For example, given [1,2,0] return 3 and [3,4,-1,1] return 2.

Your algorithm should run in O(n) time and uses constant space.

Analysis

This problem can solve by using a bucket-sort like algorithm. Let's consider finding first missing positive and 0 first. The key fact is that the ith element should be i, so we have:
i==A[i]
A[i]==A[A[i]]

For example, given an array {1,2,0,4}, the algorithm does the following: ```int firstMissingPositiveAnd0(int A[]) { int n = A.length; for (int i = 0; i < n; i++) { // when the ith element is not i while (A[i] != i) { // no need to swap when ith element is out of range [0,n] if (A[i] < 0 || A[i] >= n) break;   //handle duplicate elements if(A[i]==A[A[i]]) break; // swap elements int temp = A[i]; A[i] = A[temp]; A[temp] = temp; } }   for (int i = 0; i < n; i++) { if (A[i] != i) return i; }   return n; }```

Java Solution

This problem only considers positive numbers, so we need to shift 1 offset. The ith element is i+1.

```public int firstMissingPositive(int[] A) { int n = A.length;   for (int i = 0; i < n; i++) { while (A[i] != i + 1) { if (A[i] <= 0 || A[i] >= n) break;   if(A[i]==A[A[i]-1]) break;   int temp = A[i]; A[i] = A[temp - 1]; A[temp - 1] = temp; } }   for (int i = 0; i < n; i++){ if (A[i] != i + 1){ return i + 1; } }   return n + 1; }```
Category >> Algorithms >> Interview
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
• Jyoti Phulwani

You are mixing 2 different questions. Here question is to find first missing positive number and the link refers to finding missing number in a range of consecutive numbers

• up23

What about the XOR method from http://www.geeksforgeeks.org/find-the-missing-number/?

1) find min and max in linear time
2) let x1 = XOR from the min value to max value
3) let x2 = XOR of all values in input
4) ans is XOR of x1 and x2

``` function findMissingXor(\$inputs) { \$min = PHP_INT_MAX; \$max = -PHP_INT_MAX; \$xorInputs = 0; foreach(\$inputs AS \$v) { if (\$v \$max) \$max = \$v; \$xorInputs ^= \$v; } \$xorSum = 0; for (\$i = \$min; \$i <= \$max; \$i ++ ) { \$xorSum ^= \$i; } \$ans = \$xorInputs ^ \$xorSum; if (\$ans == 0) return \$max + 1; else return \$ans; } ```

• Billionaire
• DivyaJyoti Rajdev

if the array is [-2,-3,-4,-8], it should return 1
thus for java offset version->
return (A[n-1]<=0)? 1: A[n-1]+1;

• Risong Na

Three things:
1. The two code snippets are different in the second loop
2. Special case when n == 0
3. The final return statement should be return A == n ? n + 1 : n;
Think about 4,3,2,1 (should return 5) and 5,3,2,1 (should return 4)