Program to find first positive missing integer in range in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of sorted list of distinct integers of size n, we have to find the first positive number in range [1 to n+1] that is not present in the array.

So, if the input is like nums = [0,5,1], then the output will be 2, as 2 is the first missing number in range 1 to 5.

To solve this, we will follow these steps −

  • target := 1

  • for each i in arr, do

    • if i is same as target, then

      • target := target + 1

  • return target

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, arr):
      target = 1
      for i in arr:
         if i == target:
            target += 1
         return target
ob = Solution()
nums = [0,5,1]
print(ob.solve(nums))

Input

[0,5,1]

Output

2
raja
Published on 08-Oct-2020 13:57:35
Advertisements