First Missing Positive Problem


Description

LeetCode Problem 41.

Given an unsorted integer array nums, return the smallest missing positive integer.

You must implement an algorithm that runs in O(n) time and uses constant extra space.

Example 1:

1
2
Input: nums = [1,2,0]
Output: 3

Example 2:

1
2
Input: nums = [3,4,-1,1]
Output: 2

Example 3:

1
2
Input: nums = [7,8,9,11,12]
Output: 1

Constraints:

  • 1 <= nums.length <= 5 * 10^5
  • -2^31 <= nums[i] <= 2^31 - 1


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int len = nums.size();
        
        for (int i = 0; i < len; i ++) {
            if (nums[i] < 0 || nums[i] > len || nums[i] == i+1) 
                continue;
            int nxt = nums[i] - 1;
            while (nxt >= 0 && nxt < len && nums[nxt] != nxt+1) {
                int nxt_nxt = nums[nxt] - 1;
                nums[nxt] = nxt + 1;
                nxt = nxt_nxt;
            }
        }
        
        for (int i = 0; i < len; i ++) {
            if (nums[i] != i + 1)
                return i + 1;
        }
        return len + 1;
    }
};




Related Posts

Repeated DNA Sequences Problem

LeetCode 187. The DNA sequence is composed of a series...

Majority Element Problem

LeetCode 169. Given an array nums of size n, return...

Fraction To Recurring Decimal Problem

LeetCode 166. Given two integers representing the numerator and denominator...

Max Points On A Line Problem

LeetCode 149. Given an array of points where points[i] =...

Lru Cache Problem

LeetCode 146. Design a data structure that follows the constraints...

Longest Consecutive Sequence Problem

LeetCode 128. Given an unsorted array of integers nums, return...