Skip to content

Commit

Permalink
Merge pull request #2560 from aadil42/patch-52
Browse files Browse the repository at this point in the history
Create 0041-first-missing-positive.js
  • Loading branch information
aakhtar3 authored Sep 5, 2023
2 parents 68c0b06 + 373d910 commit 3531884
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions javascript/0041-first-missing-positive.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* Cyclic Sort
* Time O(N) | Space O(1)
* https://leetcode.com/problems/first-missing-positive
* @param {number[]} nums
* @return {number}
*/
var firstMissingPositive = (nums) => {
cyclicSort(nums);

return search(nums);
};

const cyclicSort = (nums, index = 0) => {
while (index < nums.length) {
const num = nums[index];
const indexKey = (num - 1);
const indexNum = nums[indexKey];

if (canSwap(nums, num, indexNum)) {
swap(nums, index, indexKey);
continue;
}

index += 1;
}
}

const search = (nums, index = 0) => {
while (index < nums.length) {
const num = nums[index];
const indexKey = (index + 1);

if (!isEqual(num, indexKey)) return indexKey;

index += 1;
}

return (nums.length + 1);
}

const canSwap = (nums, num, indexNum) =>
isPositive(num) &&
isInBound(num, nums) &&
!isEqual(num, indexNum);

const swap = (nums, index, indexKey) =>
[nums[index], nums[indexKey]] = [nums[indexKey], nums[index]];

const isPositive = (num) => (0 < num);

const isInBound = (num, nums) => (num <= nums.length);

const isEqual = (num, indexNum) => (num === indexNum);


0 comments on commit 3531884

Please sign in to comment.