Skip to content

Commit 52e3699

Browse files
authored
Create 0041-first-missing-positive.js
Added Solution for first-missing-positive in JS
1 parent 9d668c6 commit 52e3699

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Time O(n) | Space O(1)
3+
* @param {number[]} nums
4+
* @return {number}
5+
*/
6+
var firstMissingPositive = function(nums) {
7+
//-1 1 3 4
8+
const swap = (a,b) => {
9+
const temp = nums[a];
10+
nums[a] = nums[b];
11+
nums[b] = temp;
12+
}
13+
// swap positions
14+
for(let i = 0; i < nums.length; i++) {
15+
const el = nums[i];
16+
const chair = el - 1;
17+
if(el >= 1 && el <= nums.length + 1 && nums[chair] !== el) {
18+
swap(chair, i);
19+
i--; // this decrement is important // check this input [3,4,-1,1]
20+
}
21+
}
22+
23+
24+
for(let i = 0; i < nums.length; i++) {
25+
if(nums[i] !== i+1) return i+1;
26+
}
27+
28+
return nums.length + 1;
29+
};
30+
31+
/**
32+
* https://leetcode.com/problems/first-missing-positive/
33+
* Time O(n) | Space O(n)
34+
* @param {number[]} nums
35+
* @return {number}
36+
*/
37+
var firstMissingPositive1 = function(nums) {
38+
39+
const numberSet = new Set(nums);
40+
41+
let i = 1;
42+
while(numberSet.has(i)) {
43+
i++;
44+
}
45+
46+
return i;
47+
};

0 commit comments

Comments
 (0)