First Missing Positive in Python

The First Missing Positive problem asks us to find the smallest missing positive integer from an unsorted array. For example, given the array [4, -3, 1, -1], the result is 2 since 1 is present but 2 is missing.

Algorithm Approach

We use a cyclic sort approach to solve this efficiently:

  • Add a 0 at the beginning to handle 1-based indexing

  • Place each positive number at its correct index position

  • Scan the array to find the first missing positive

Example Implementation

Here's the complete solution using cyclic sort ?

class Solution:
    def firstMissingPositive(self, nums):
        # Add 0 at beginning for 1-based indexing
        nums = [0] + nums
        
        # Place each number at its correct index
        for i in range(len(nums)):
            while (nums[i] >= 0 and 
                   nums[i] < len(nums) and 
                   nums[nums[i]] != nums[i]):
                # Swap nums[i] with nums[nums[i]]
                nums[nums[i]], nums[i] = nums[i], nums[nums[i]]
        
        # Find first missing positive
        num = 1
        for i in range(1, len(nums)):
            if num == nums[i]:
                num += 1
        
        return num

# Test the solution
solution = Solution()
result = solution.firstMissingPositive([4, -3, 1, -1])
print("First missing positive:", result)
First missing positive: 2

How It Works

Let's trace through the example [4, -3, 1, -1]:

def trace_algorithm(nums):
    print("Original array:", nums)
    nums = [0] + nums
    print("After adding 0:", nums)
    
    # Cyclic sort phase
    for i in range(len(nums)):
        while (nums[i] >= 0 and 
               nums[i] < len(nums) and 
               nums[nums[i]] != nums[i]):
            print(f"Swapping nums[{nums[i]}] with nums[{i}]")
            nums[nums[i]], nums[i] = nums[i], nums[nums[i]]
            print("Array now:", nums)
    
    print("After sorting:", nums)
    
    # Find missing positive
    num = 1
    for i in range(1, len(nums)):
        if num == nums[i]:
            num += 1
    
    print("First missing positive:", num)
    return num

trace_algorithm([4, -3, 1, -1])
Original array: [4, -3, 1, -1]
After adding 0: [0, 4, -3, 1, -1]
Swapping nums[4] with nums[1]
Array now: [0, -1, -3, 1, 4]
Array now: [0, -1, -3, 1, 4]
After sorting: [0, -1, -3, 1, 4]
First missing positive: 2

Alternative Approach

A simpler approach using a set for smaller arrays ?

def first_missing_positive_simple(nums):
    # Create set of positive numbers
    positive_nums = set(num for num in nums if num > 0)
    
    # Find first missing positive starting from 1
    missing = 1
    while missing in positive_nums:
        missing += 1
    
    return missing

# Test both approaches
test_cases = [[4, -3, 1, -1], [1, 2, 0], [3, 4, -1, 1], [7, 8, 9, 11, 12]]

for nums in test_cases:
    result = first_missing_positive_simple(nums)
    print(f"Array: {nums} ? First missing positive: {result}")
Array: [4, -3, 1, -1] ? First missing positive: 2
Array: [1, 2, 0] ? First missing positive: 3
Array: [3, 4, -1, 1] ? First missing positive: 2
Array: [7, 8, 9, 11, 12] ? First missing positive: 1

Comparison

Approach Time Complexity Space Complexity Best For
Cyclic Sort O(n) O(1) Large arrays, space-constrained
Set-based O(n) O(n) Small arrays, simplicity

Conclusion

The cyclic sort approach efficiently finds the first missing positive in O(n) time with O(1) extra space. For simpler cases, the set-based approach offers better readability at the cost of additional memory usage.

Updated on: 2026-03-25T08:37:48+05:30

991 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements