41. First Missing Positive

ArrayHash Table

Explanation

To solve this problem in O(n) time and O(1) auxiliary space, we can utilize the array itself to keep track of the missing positive integers. We iterate through the array and place each element at its correct position (i.e., nums[i] should be placed at index nums[i] - 1). After the rearrangement, we then iterate through the array again to find the first index where the value does not match the index (indicating a missing positive integer). If no such index is found, then the missing integer is one more than the length of the array.

Time Complexity: O(n)
Space Complexity: O(1)

class Solution {
    public int firstMissingPositive(int[] nums) {
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
                int temp = nums[nums[i] - 1];
                nums[nums[i] - 1] = nums[i];
                nums[i] = temp;
            }
        }
        
        for (int i = 0; i < n; i++) {
            if (nums[i] != i + 1) {
                return i + 1;
            }
        }
        
        return n + 1;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.