Skip to main content

Command Palette

Search for a command to run...

Problem: First Missing Positive

Updated
•1 min read•View as Markdown
A

({MERN Stack Developer at mackph}) | <Ex-Internshala Student Partner(ISP 16)> | <5 star coder at Hackerrank> | <Self employed at Mackph> | <GSSoC '22 Contributor> | <Ex-Campus Ambassador at International MUN>

Given an unsorted integer array nums, return the smallest missing positive integer.

You must implement an algorithm that runs in O(n) time and uses constant extra space.

Example 1:

  Input: nums = [1,2,0]
  Output: 3

Example 2:

   Input: nums = [3,4,-1,1]
   Output: 2

Screenshot 2022-08-10 115255.png

Screenshot 2022-08-10 115324.png

```class Solution { public int firstMissingPositive(int[] nums) { Arrays.sort(nums);

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

        }
        if(nums[i] != i+1 - m)  return i+1-m;

    }

}

return nums.length + 1-m;

} } ```

More from this blog

mackph's blog

40 posts