
Problem
Solution
Submissions
First Missing Positive
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to find the smallest missing positive integer in an unsorted array. The algorithm must run in O(n) time and use constant extra space. For example, the first missing positive integer in [1, 2, 0] is 3.
Example 1
- Input: nums = [1, 2, 0]
- Output: 3
- Explanation: The array contains positive integers 1 and 2. The smallest positive integer is 1, which is present. The next positive integer is 2, which is also present. The next positive integer is 3, which is not present. Therefore, 3 is the first missing positive integer.
Example 2
- Input: nums = [3, 4, -1, 1]
- Output: 2
- Explanation: The array contains positive integers 3, 4, and 1. The smallest positive integer is 1, which is present. The next positive integer is 2, which is not present. Therefore, 2 is the first missing positive integer.
Constraints
- 0 <= nums.length <= 10^5
- -2^31 <= nums[i] <= 2^31 - 1
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use the array itself as a hash table to mark the presence of positive integers
- Observe that the answer will always be between 1 and n+1, where n is the array length
- For each positive integer i ≤ n in the array, mark the presence of i by negating the value at index i-1
- After processing all elements, the first index i where the value is positive indicates that i+1 is missing
- Handle edge cases carefully, including negative numbers and numbers greater than n