Skip to content

Commit 9762c8e

Browse files
committed
Missing Number solution
1 parent 4372706 commit 9762c8e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

missing-number/kimyoung.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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

0 commit comments

Comments
 (0)