simple c# with O(n) space


  • 0
    V

    Uses a hashSet
    Go through the given array and find the MaxPositiveNumber in the array while adding all the positive numbers to a hashSet. (Ignore negative numbers when adding to hashSet)
    Then, loop from 1 to the MaxPositiveNumber and see if the number is present in the hashSet. The first missing number is your answer

    public class Solution {
    public int FirstMissingPositive(int[] nums) {

        if(nums.Length == 0)
        {
            return 1;
        }
        
        int result = -1;
        
        var hashSet = new HashSet<int>();
        int maxPositiveNumber = 0;
        
        for(int i = 0; i < nums.Length; i++)
        {
            if(nums[i] > maxPositiveNumber)
            {
                maxPositiveNumber = nums[i];
            }
            
            if(nums[i] > 0)
            {
                hashSet.Add(nums[i]);
            }
        }
        
        for(int i = 1; i<=maxPositiveNumber; i++)
        {
            if(!hashSet.Contains(i))
            {
                result = i;
                break;
            }
        }
        
        if(result < 0)
        {
            result = maxPositiveNumber + 1;
        }
        
        return result;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.