First Missing Positive in TypeScript

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

    // Step 1: Place each number in its correct position
    for (let i = 0; i < n; i++) {
        // Swap the numbers to their correct positions
        while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
            // Swap nums[i] with nums[nums[i] - 1]
            let temp = nums[nums[i] - 1];
            nums[nums[i] - 1] = nums[i];
            nums[i] = temp;
        }
    }

    // Step 2: Find the first missing positive integer
    for (let i = 0; i < n; i++) {
        if (nums[i] !== i + 1) {
            // The missing number is i + 1
            return i + 1;
        }
    }

    // If all numbers are present in sequence, the missing number is n + 1
    return n + 1;
}

PrevNext