@@ -30,28 +30,52 @@ var maxArea = function (height) {
30
30
} ;
31
31
32
32
// trapping rain water
33
- var trap = function ( height ) {
33
+ var trap = function ( height ) {
34
34
if ( height . length === 0 ) return 0 ;
35
35
// two pointer and correspoding variables
36
- let left = 0 , leftMax = 0 ;
37
- let right = height . length - 1 , rightMax = 0 ;
36
+ let left = 0 ,
37
+ leftMax = 0 ;
38
+ let right = height . length - 1 ,
39
+ rightMax = 0 ;
38
40
let waterTrapped = 0 ;
39
- while ( left < right ) {
40
- if ( height [ left ] < height [ right ] ) {
41
- if ( height [ left ] >= leftMax ) {
41
+ while ( left < right ) {
42
+ if ( height [ left ] < height [ right ] ) {
43
+ if ( height [ left ] >= leftMax ) {
42
44
leftMax = height [ left ] ;
43
- } else {
45
+ } else {
44
46
waterTrapped += leftMax - height [ left ]
45
47
}
46
48
left ++ ;
47
- } else {
48
- if ( height [ right ] >= rightMax ) {
49
+ } else {
50
+ if ( height [ right ] >= rightMax ) {
49
51
rightMax = height [ right ] ;
50
- } else {
52
+ } else {
51
53
waterTrapped += rightMax - height [ right ]
52
54
}
53
55
right -- ;
54
56
}
55
57
}
56
58
return waterTrapped ;
59
+ } ;
60
+
61
+ // first missing positive
62
+ var firstMissingPositive = function ( nums ) {
63
+ let n = nums . length ;
64
+ // Place the numbers in thier correct position
65
+ for ( let i in nums ) {
66
+ // while the number is in range but not in correct position
67
+ while ( nums [ i ] > 0 && nums [ i ] <= n && nums [ nums [ i ] - 1 ] !== nums [ i ] ) {
68
+ // swap number at i with its correct position
69
+ let correctIndex = nums [ i ] - 1 ;
70
+ [ nums [ i ] , nums [ correctIndex ] ] = [ nums [ correctIndex ] , nums [ i ] ]
71
+ }
72
+ }
73
+ // Identify the first missing positive integer
74
+ for ( let i = 0 ; i < n ; i ++ ) {
75
+ if ( nums [ i ] !== i + 1 ) {
76
+ return i + 1 ;
77
+ }
78
+ }
79
+ // If all numbers are at their correct position return i+1
80
+ return n + 1 ;
57
81
} ;
0 commit comments