Program to find first positive missing integer in range in Python

Suppose we have a list of sorted 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 4.

Algorithm

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

Example

Let us see the following implementation to get better understanding ?

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("Input:", nums)
print("Output:", ob.solve(nums))
Input: [0, 5, 1]
Output: 2

How It Works

The algorithm works by maintaining a target variable that represents the next positive integer we're looking for. As we iterate through the sorted array, whenever we find the current target value, we increment the target. Since the array is sorted, once we skip over a target value, we know it's missing from the sequence.

Another Example

Let's test with a different input to see how it handles various cases ?

class Solution:
    def solve(self, arr):
        target = 1
        for i in arr:
            if i == target:
                target += 1
        return target

ob = Solution()

# Test with consecutive numbers starting from 1
nums1 = [1, 2, 3, 4]
print("Input:", nums1)
print("First missing positive:", ob.solve(nums1))

# Test with gaps in sequence
nums2 = [1, 3, 6, 4, 1, 2]
print("Input:", nums2)
print("First missing positive:", ob.solve(nums2))
Input: [1, 2, 3, 4]
First missing positive: 5
Input: [1, 3, 6, 4, 1, 2]
First missing positive: 5

Conclusion

This algorithm efficiently finds the first missing positive integer by tracking the next expected value. The time complexity is O(n) and space complexity is O(1), making it an optimal solution for this problem.

Updated on: 2026-03-25T11:08:36+05:30

399 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements