151 DSA Problem journey

151 DSA Problem journey

First Missing Positive

Q11: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 O(1) auxiliary space.

Example :

Input: nums = [1,2,0]
Output: 3
Explanation: The numbers in the range [1,2] are all in the array.

Solution:
class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
         int n = nums.size();
        for (int i = 0; i < n; i++) if (nums[i] <= 0) nums[i] = n + 1;
        for (int i = 0; i < n; i++) if (abs(nums[i]) <= n && 
        nums[abs(nums[i]) - 1] > 0) nums[abs(nums[i]) - 1] *= -1;
        for (int i = 0; i < n; i++) if (nums[i] > 0) return i + 1;
        return n + 1;

    }
};

Explantion:
The provided C++ code aims to find the smallest positive integer missing in a 
given array. The firstMissingPositive function is designed to achieve this, 
taking an array of integers as input and returning the identified missing 
positive integer. The algorithm preprocesses the array by replacing 
non-positive values with numbers greater than the array size. It then marks 
the presence of positive integers by negating values at corresponding indices.
 The identification of the missing positive is achieved by returning the index 
+ 1 of the first positive value encountered. If the array contains all positive
 integers from 1 to n, the function returns n + 1. The algorithm demonstrates a
 time complexity of O(n) due to three passes through the array and a space 
complexity of O(1) as it modifies the array in-place. 
This solution effectively addresses the task of finding the first missing 
positive integer within the given array.

Did you find this article valuable?

Support Gaurav Coding Blogs by becoming a sponsor. Any amount is appreciated!