Tutorialspoint
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
ArraysNumberEYLTIMindtree
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Replace all non-positive numbers and numbers greater than n with n+1 as placeholder.

 Step 2: Iterate through array and use absolute values to avoid interference from our marking.
 Step 3: For each valid number x, mark nums[x-1] as negative to indicate presence of x.
 Step 4: Iterate through the modified array to find the first positive element.
 Step 5: The index of first positive element plus 1 is the missing positive number.
 Step 6: If all positions are marked negative, then numbers 1 to n are present.
 Step 7: Return n+1 as the first missing positive number in that case.

Submitted Code :