Program to find lowest possible integer that is missing in the array in Python


Suppose we have a list of numbers called nums, we have to find the first missing positive number. In other words, the lowest positive number that does not present in the array. The array can contain duplicates and negative numbers as well.

So, if the input is like nums = [0,3,1], then the output will be 2

To solve this, we will follow these steps −

  • nums := a set with all positive numbers present in nums

  • if nums is null, then

    • return 1

  • for i in range 1 to size of nums + 2, do

    • if i is not present in nums, then

    • return i

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      nums = set(num for num in nums if num > 0)

      if not nums:
         return 1
      for i in range(1, len(nums) + 2):
         if i not in nums:
            return i
ob = Solution()
nums = [0,3,1]
print(ob.solve(nums))

Input

[0,3,1]

Output

2

Updated on: 08-Oct-2020

110 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements