First Missing Positive — LeetCode 41 Python Solution

HardArrayHash Table
Problem
#41
Pattern
Hash Map
Reading time
2 min

The problem

Given an unsorted integer array nums. Return the smallest positive integer that is not present in nums.

Example

Input
nums = [1,2,0]
Output
3
Explanation
The numbers in the range [1,2] are all in the array.

Python solution

Python
class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        n = len(nums)
        for i in range(n):
            while 1 <= nums[i] <= n and nums[i] != nums[nums[i] - 1]:
                j = nums[i] - 1
                nums[i], nums[j] = nums[j], nums[i]
        for i in range(n):
            if nums[i] != i + 1:
                return i + 1
        return n + 1

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 41. First Missing Positive is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 41. First Missing Positive?
LeetCode 41. First Missing Positive is rated Hard on LeetCode.
What is the time complexity of LeetCode 41. First Missing Positive?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 41. First Missing Positive?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 41. First Missing Positive cover?
LeetCode 41. First Missing Positive is tagged Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview