File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ var missingNumber = function ( nums ) { // brute force approach
2
+ let missingNumber ;
3
+ for ( let i = 0 ; i < nums . length ; i ++ ) {
4
+ if ( nums . indexOf ( i ) === - 1 ) missingNumber = i ;
5
+ }
6
+ return missingNumber === undefined ? nums . length : missingNumber ;
7
+ } ;
8
+
9
+ // time - O(n^2) finding the index of i while iterating through nums
10
+ // splace - O(1) no extra space needed other than missingNumber which just stores the result
11
+
12
+ var missingNumber = function ( nums ) { // set approach
13
+ let set = new Set ( nums ) ;
14
+ for ( let i = 0 ; i < nums . length + 1 ; i ++ ) {
15
+ if ( ! set . has ( i ) ) return i ;
16
+ }
17
+ } ;
18
+
19
+ // time - O(n) looping through nums to find the missing number
20
+ // splace - O(n) creating a set of nums
21
+
22
+ var missingNumber = function ( nums ) { // mathematical approach
23
+ const len = nums . length
24
+ const expectedSum = len * ( len + 1 ) / 2 ;
25
+ const actualSum = nums . reduce ( ( acc , el ) => acc += el , 0 ) ;
26
+ return expectedSum - actualSum ;
27
+ } ;
28
+
29
+ // time - O(n) reduce method on actualSum
30
+ // space - O(1) extra space irrelevant to input
You can’t perform that action at this time.
0 commit comments