Skip to main content
  1. Problem Solving Solutions/

First Missing Positive LeetCode Solution

·1 min read
Leetcode
Mayukh Datta
Author
Mayukh Datta
Table of Contents

Problem: https://leetcode.com/problems/first-missing-positive/

Solution in C++
#

class Solution { public: int firstMissingPositive(vector& nums) { int n = nums.size();

    int i = 0;
    while(i < n) {
        if(nums\[i\] > 0 && nums\[i\] <= n && nums\[i\] != nums\[nums\[i\] - 1\]) {
            swap(nums\[i\], nums\[nums\[i\] - 1\]);
            // we swap ith element with the
            // element at position (ith element - 1)
            // because we have 0-based indexing
        }else{
            i++;
        }
    }
    
    for(int i=0; i<n; i++) {
        if(nums\[i\] != i + 1) {
            return i + 1;
        }
    }
    
    return n + 1;
}

};