KatInterview

41. First Missing Positive

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the smallest missing positive integer from an unsorted array. The constraints are strict: O(n) time and O(1) auxiliary space. This implies we cannot use sorting (which is O(n log n)) or an auxiliary data structure like a hash set (which would be O(n) space). The key insight is to use the array itself to store information about the presence of numbers. Since we are looking for the smallest missing positive integer, we are only concerned with numbers from 1 up to n, where n is the length of the array. The answer must be in the range [1, n+1].

Solution

First Missing Positive in Python

class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        n = len(nums)
        
        # Step 1: Use cyclic sort to place positive integers in their correct positions.
        # The number k (if it's in the range [1, n]) should be at index k-1.
        i = 0
        while i < n:
            current_num = nums[i]
            
            # We are interested in numbers in the range [1, n].
            # If current_num is in this range AND it's not in its correct place.
            # Correct place for `current_num` is index `current_num - 1`.
            # The check `nums[current_num - 1] != current_num` also handles duplicates.
            if 1 <= current_num <= n and nums[current_num - 1] != current_num:
                # Swap it with the element at its correct place.
                # Python's tuple swapping is convenient.
                nums[i], nums[current_num - 1] = nums[current_num - 1], nums[i]
                # After swapping, the new nums[i] needs to be checked again, so we don't increment i.
            else:
                # If current_num is not a positive integer in the range [1, n],
                # or if it's already in its correct place, we move to the next index.
                i += 1

        # Step 2: Find the first missing positive integer.
        # After sorting, the first index `i` where nums[i] != i + 1
        # means that i + 1 is the smallest missing positive integer.
        for i in range(n):
            if nums[i] != i + 1:
                return i + 1
        
        # Step 3: If all numbers from 1 to n are present, the answer is n + 1.
        return n + 1

First Missing Positive in Java

class Solution {
    public int firstMissingPositive(int[] nums) {
        int n = nums.length;
        
        // Step 1: Use cyclic sort to place positive integers in their correct positions.
        // The number k (if it's in the range [1, n]) should be at index k-1.
        int i = 0;
        while (i < n) {
            int current_num = nums[i];
            
            // We are interested in numbers in the range [1, n].
            // If current_num is in this range AND it's not in its correct place.
            // Correct place for `current_num` is index `current_num - 1`.
            if (current_num > 0 && current_num <= n && nums[current_num - 1] != current_num) {
                // Swap it with the element at its correct place.
                int temp = nums[current_num - 1];
                nums[current_num - 1] = current_num;
                nums[i] = temp;
                // After swapping, the new nums[i] needs to be checked again, so we don't increment i.
            } else {
                // If current_num is not a positive integer in the range [1, n],
                // or if it's already in its correct place, we move to the next index.
                i++;
            }
        }
        
        // Step 2: Find the first missing positive integer.
        // After sorting, the first index `i` where nums[i] != i + 1
        // means that i + 1 is the smallest missing positive integer.
        for (i = 0; i < n; i++) {
            if (nums[i] != i + 1) {
                return i + 1;
            }
        }
        
        // Step 3: If all numbers from 1 to n are present, the answer is n + 1.
        return n + 1;
    }
}

First Missing Positive in C++

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int n = nums.size();
        
        // Step 1: Use cyclic sort to place positive integers in their correct positions.
        // The number k (if it's in the range [1, n]) should be at index k-1.
        int i = 0;
        while (i < n) {
            // The number at the current index.
            int current_num = nums[i];
            
            // We are interested in numbers in the range [1, n].
            // If current_num is in this range AND it's not in its correct place.
            // Correct place for `current_num` is index `current_num - 1`.
            if (current_num > 0 && current_num <= n && nums[current_num - 1] != current_num) {
                // Swap it with the element at its correct place.
                // After swapping, the new nums[i] needs to be checked again, so we don't increment i.
                std::swap(nums[i], nums[current_num - 1]);
            } else {
                // If current_num is not a positive integer in the range [1, n],
                // or if it's already in its correct place, we move to the next index.
                i++;
            }
        }
        
        // Step 2: Find the first missing positive integer.
        // After sorting, the first index `i` where nums[i] != i + 1
        // means that i + 1 is the smallest missing positive integer.
        for (i = 0; i < n; ++i) {
            if (nums[i] != i + 1) {
                return i + 1;
            }
        }
        
        // Step 3: If all numbers from 1 to n are present, the answer is n + 1.
        return n + 1;
    }
};

First Missing Positive in TypeScript

function firstMissingPositive(nums: number[]): number {
    const n = nums.length;

    // Step 1: Use cyclic sort to place positive integers in their correct positions.
    // The number k (if it's in the range [1, n]) should be at index k-1.
    let i = 0;
    while (i < n) {
        const current_num = nums[i];

        // We are interested in numbers in the range [1, n].
        // If current_num is in this range AND it's not in its correct place.
        // Correct place for `current_num` is index `current_num - 1`.
        if (current_num > 0 && current_num <= n && nums[current_num - 1] !== current_num) {
            // Swap it with the element at its correct place.
            // Using destructuring assignment for swapping.
            [nums[i], nums[current_num - 1]] = [nums[current_num - 1], nums[i]];
            // After swapping, the new nums[i] needs to be checked again, so we don't increment i.
        } else {
            // If current_num is not a positive integer in the range [1, n],
            // or if it's already in its correct place, we move to the next index.
            i++;
        }
    }

    // Step 2: Find the first missing positive integer.
    // After sorting, the first index `i` where nums[i] != i + 1
    // means that i + 1 is the smallest missing positive integer.
    for (i = 0; i < n; i++) {
        if (nums[i] !== i + 1) {
            return i + 1;
        }
    }

    // Step 3: If all numbers from 1 to n are present, the answer is n + 1.
    return n + 1;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.