> For the complete documentation index, see [llms.txt](https://anand-aryan.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://anand-aryan.gitbook.io/leetcode/41.-first-missing-positive.md).

# 41. First Missing Positive

First Missing Positive

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.

## Solution <a href="#solution" id="solution"></a>

```java
public class Solution {
    public int firstMissingPositive(int[] nums) {

       for (int i = 0; i < nums.length; ) {
            if (nums[i] > 0 && i != nums[i] - 1 && nums[i] -1 < nums.length && nums[nums[i] -1] != nums[i]) {
                swap(nums, nums[i] - 1, i);
            } else{
                i ++;
            }
        }

        for(int i = 0; i < nums.length; i ++) {
            if (nums[i] !=i+1)
                return i+1;
        }

        return nums.length + 1;
    }

    public static void swap(int[] nums, int i, int j) {
        int temp = nums[i];

        nums[i] = nums[j];
        nums[j] = temp;
    }


}
```
