AlgoMaster Logo

First Missing Positive

Ashish

Ashish Pratap Singh

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

Intuition:

  • We need to find the first missing positive integer from an unsorted array.
  • Our basic approach involves checking starting from 1, then 2, and so on, whether each number is present in the array.
  • We continue this process until we find a number that is not present, which will be our answer.

Steps:

  1. Start with the integer 1.
  2. For each integer, check if it exists in the array by iterating through the entire array.
  3. If the integer is found, increment to check the next integer.
  4. If an integer is not found, it is the first missing positive number.

Code:

2. HashSet Approach

Intuition:

  • Rather than checking every number by iterating through the array, we can store all numbers in a HashSet for O(1) look-up time.
  • Iterate through numbers starting from 1 and check if they are in the HashSet.

Steps:

  1. Insert all numbers into a HashSet.
  2. Start checking integers from 1 onwards.
  3. If any integer is not found in the HashSet, that's the first missing positive number.

Code:

3. Cyclic Sort Approach

Intuition:

  • Place each number at its correct index (i.e., number 1 at index 0, number 2 at index 1, etc.). Numbers out of this range can be ignored.
  • Finally, the first place where the number is not equal to the index + 1 is the missing number.

Steps:

  1. Iterate through the array and swap numbers to their correct positions if they are within the valid range (1 to n).
  2. After sorting, iterate again to find the first index where the number is not equal to index + 1.
  3. Return index + 1 as the result.

Code: