Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

41. First Missing Positive #102

Merged
merged 4 commits into from
Oct 22, 2024

Conversation

chhavibansal
Copy link
Contributor

@chhavibansal chhavibansal commented Oct 22, 2024

Title of the problem

41. First Missing Positive

Checklist before requesting a review

  • I have checked the guide for contributions.
  • I have added the description at the top of the solution file.
  • I have added a test file for the problem.
  • I have added an entry to the README file with a link to the new file.
  • I have run linter (npx eslint LeetcodeProblems LeetcodeProblemsTests) and unit tests (node Test.js) and they pass. More info.

Check the guide and this PR example.

Copy link
Owner

@ignacio-chiazzo ignacio-chiazzo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Love it! I gave the problem a try before reading your solution and this is what I came up with:

var firstMissingPositive = function(nums) {
    length = nums.length;

    // put the values i in position i + 1 (e.g. 3 in nums[4])
    var i = 0;
    while(i < length) {
        var value = nums[i]
        if(value <= nums.length && value > 0) {
            if (value != i + 1 && nums[value - 1] != value) {
                swap(nums, value - 1, i)
            } else {
                i++;
            }
        } else {
            i++;
        }
    }

    // find missing position
    var j = 0;
    while(j < length) {
        if(nums[j] != j + 1) {
            return j + 1;
        }
        j++;
    }

    return length + 1; 
};

var swap = function(nums, i, j) {
    var tmp = nums[i];
    nums[i] = nums[j]
    nums[j] = tmp;
}

@ignacio-chiazzo ignacio-chiazzo merged commit 48aaef0 into ignacio-chiazzo:master Oct 22, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants