LeetCode 41: First Missing Positive Solution
Master LeetCode problem 41 (First Missing Positive), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
41. First Missing Positive
Problem Explanation
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)
Solution Code
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;
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 41 (First Missing Positive)?
This page provides optimized solutions for LeetCode problem 41 (First Missing Positive) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 41 (First Missing Positive)?
The time complexity for LeetCode 41 (First Missing Positive) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 41 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 41 in Java, C++, or Python.