First Missing Positive in Python

PythonServer Side ProgrammingProgramming

Suppose we have one unsorted integer array; we have to find the smallest missing positive number. So if the array is like [4, -3, 1, -1], then the result will be 2.

To solve this, we will follow these steps −

  • set i := 0 and update array nums by adding one 0 before all numbers

  • for i in range 0 to length of nums

    • while nums[i] >= 0 and nums[i] < length of nums and nums[nums[i]] is not nums[i] −

      • nums[nums[i]] := nums[i]

      • nums[i] := nums[nums[i]]

  • num := 1

  • for i in range 1 to length of nums

    • if num = nums[i], then increase num by 1

  • return num

Example

Let us see the following implementation to get better understanding −

 Live Demo

class Solution(object):
   def firstMissingPositive(self, nums):
   i = 0
   nums = [0] + nums
   for i in range(len(nums)):
      while nums[i]>=0 and nums[i]<len(nums) and nums[nums[i]]!=nums[i]:
         nums[nums[i]],nums[i] = nums[i],nums[nums[i]]
      num = 1
      for i in range(1,len(nums)):
         if num == nums[i]:
            num+=1
      return num

ob = Solution()
print(ob.firstMissingPositive([4,-3,1,-1]))

Input

[4,-3,1,-1]

Output

2
raja
Published on 26-May-2020 11:49:29
Advertisements