Tutorialspoint
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)
ArraysTutorixArctwist
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 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

Steps to solve by this approach:

 Step 1: Observe that the first missing positive must be between 1 and n+1, where n is the array length.

 Step 2: The goal is to place each positive number i at index i-1 (e.g., 1 at index 0, 2 at index 1, etc.).
 Step 3: Iterate through the array and use swapping to place each positive number i at index i-1 if possible.
 Step 4: Skip numbers that are negative, zero, greater than n, or already in their correct position.
 Step 5: After rearrangement, iterate through the array again to find the first position i where the value is not i+1.
 Step 6: If all positions are correctly filled, the answer is n+1.
 Step 7: Return the first missing positive integer.

Submitted Code :