Python Solution For First Missing Positive


  • 0
    T

    Hi LeetCoders,

    I am new here.Posting my first solution in python (BTW I'm .net developer but learning to code in python)

    Steps -

    1. sort the given input array in ascending order.
      nums.sort()

    2. return 1 by default in following cases:
      i] if given array is null or empty or count =0
      ii] if given array has one integer and its 0
      iii]if given array contains negative integer and not 1

     if (len(nums) == 0 or (len(nums) == 1 and nums[0] == 0) or  (nums[0]<0 and (1 not in nums))):
                return 1 
    

    3.take one empty array
    sortednum = []

    4.Append all postive integer from input to sortednum[] (including 0)

                  if (i >= 0 and i not in sortednum):
                    sortednum.append(i)  
    
    1. sort sortednum in ascending order
      sortednum.sort()

    2. return 1 in following case

    if(len(sortednum)==1 and first!=1):
                                    return 1
    
    1. take first and last variable as follows
        first=sortednum[0]
            last=0
    
    1. set last variable
     if(len(sortednum)==1):
                last=first+1
            else:
                last = sortednum[len(sortednum)-1]
    

    9.for loop to get first missing positive

        for i in range(first,last+1):
              if i in sortednum:      
               
                if (i - 1 > 0 and (i-1 not in sortednum)):
                   
                    return i - 1
    
                else:
                   
                    if ((i+1)not in sortednum):
                        return i + 1
    

  • 0
    S
        def f_miss(input):
            for i in range(1, len(input)+1):
                if i not in input:
                    print('Missing',i)
                    break
    

Log in to reply
 

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