Skip to content

Commit 33aacde

Browse files
committed
Add missing-number solution
1 parent f9a83e7 commit 33aacde

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

missing-number/Jeehay28.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
6+
// *** Guided approach 2: bitwise operations and avoids potential overflow issues with very large sums
7+
// XOR method
8+
// Time complexity: O(n)(two loops: one for numbers 0 to n and one for array elements)
9+
// Space complexity: O(1)
10+
11+
var missingNumber = function (nums) {
12+
// XOR with itself results in 0 : a xor a = 0
13+
// XOR with 0 results in the number itself : a xor 0 = a
14+
// XOR is commutative and associative
15+
16+
const n = nums.length;
17+
18+
let xor = 0;
19+
20+
for (let i = 0; i <= n; i++) {
21+
xor ^= i;
22+
}
23+
24+
for (any of nums) {
25+
xor ^= any;
26+
}
27+
28+
return xor;
29+
};
30+
31+
// *** Guided approach 1: simplicity and clarity
32+
// Gauss' Formula (Sum of First n Numbers): n*(n+1) / 2
33+
// Time complexity: O(n)
34+
// Space complexity: O(1)
35+
// var missingNumber = function (nums) {
36+
// const n = nums.length;
37+
// const expectedSum = (n * (n + 1)) / 2;
38+
// const actualSum = nums.reduce((acc, cur) => acc + cur, 0); // O(n)
39+
40+
// const missingNum = expectedSum - actualSum;
41+
42+
// return missingNum;
43+
// };
44+
45+
// *** My own approach
46+
// Time complexity: O(n^2)
47+
// Space complexity: O(n)
48+
// var missingNumber = function (nums) {
49+
50+
// let distinctNums = new Set([]);
51+
52+
// for (any of nums) {
53+
// if (distinctNums.has(any)) {
54+
// return
55+
// } else {
56+
// distinctNums.add(any)
57+
// }
58+
// }
59+
60+
// const n = distinctNums.size;
61+
62+
// for (let i = 0; i <= n; i++) {
63+
// if (!nums.includes(i)) {
64+
// return i;
65+
// }
66+
// }
67+
68+
// };

0 commit comments

Comments
 (0)