Tutorialspoint
Problem
Solution
Submissions

Smallest Missing Positive Integer

Certification: Basic Level Accuracy: 66.67% Submissions: 3 Points: 5

Write a C# program to find the smallest missing positive integer in an unsorted array of integers. Your algorithm should run in O(n) time and use constant extra space.

Example 1
  • Input: nums = [1, 2, 0]
  • Output: 3
  • Explanation:
    • Step 1: Replace all non-positive numbers and numbers greater than the array length (n=3) with a value outside the valid range (e.g., 4).
    • Step 2: Use the array itself as a hash table by marking the presence of each valid positive number by making the value at index (i-1) negative.
    • Step 3: After marking, the array would have presence of 1 and 2 indicated.
    • Step 4: Find the first index i where the value is positive, which corresponds to the first missing positive integer i+1.
    • Step 5: Since 1 and 2 are present, 3 is the smallest missing positive integer.
Example 2
  • Input: nums = [3, 4, -1, 1]
  • Output: 2
  • Explanation:
    • Step 1: Replace all non-positive numbers (-1) and numbers greater than the array length (n=4), which are 3 and 4, with a value outside the valid range (e.g., 5).
    • Step 2: Use the array itself as a hash table by marking the presence of each valid positive number.
    • Step 3: After marking, the array would have presence of 1 indicated but not 2.
    • Step 4: Find the first index i where the value is positive, which corresponds to index 1 (for number 2).
    • Step 5: Since 1 is present but 2 is not, 2 is the smallest missing positive integer.
Constraints
  • 1 ≤ nums.length ≤ 10⁵
  • -2³¹ ≤ nums[i] ≤ 2³¹ - 1
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysControl StructuresWalmartPhillips
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 numbers
  • Ignore all numbers that are out of range (non-positive or greater than array length)
  • Use the sign of values at particular indices to mark the presence of positive numbers
  • Scan the array again to find the first index with a positive value
  • Handle edge cases carefully

Steps to solve by this approach:

 Step 1: Replace non-positive numbers and numbers > n with n+1 (as they won't affect the result).
 Step 2: Use the array indices to mark presence of positive numbers (make nums[i-1] negative if number i is present).
 Step 3: Iterate through the array and find the first positive value at index i, return i+1.
 Step 4: If all indices contain negative values, return n+1.
 Step 5: Handle edge cases like empty arrays or arrays with duplicates.

Submitted Code :