
Problem
Solution
Submissions
First Missing Positive
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to find the smallest missing positive integer from an unsorted integer array. Given an unsorted integer array nums, return the smallest positive integer that is not present in nums. The solution must run in O(n) time and use only constant extra space.
Example 1
- Input: nums = [1, 2, 0]
- Output: 3
- Explanation: The array contains [1, 2, 0]. The smallest positive integers are 1, 2, 3, 4, ... Since 1 and 2 are present but 3 is missing, return 3.
Example 2
- Input: nums = [3, 4, -1, 1]
- Output: 2
- Explanation: The array contains [3, 4, -1, 1]. The smallest positive integers are 1, 2, 3, 4, ... Since 1 is present but 2 is missing, return 2.
Constraints
- 1 ≤ nums.length ≤ 5 * 10^5
- -2^31 ≤ nums[i] ≤ 2^31 - 1
- Time Complexity: O(n)
- Space Complexity: O(1)
- Must modify the input array in-place
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 presence of positive integers
- First, replace all non-positive numbers and numbers greater than n with a placeholder
- Use the sign of array elements to mark presence of numbers
- For each number x in range [1, n], mark nums[x-1] as negative
- The first positive element's index + 1 is the missing positive number