Skip to content

Commit e9f7993

Browse files
committed
😈 [268] Online solutions - XOR / subtract
1 parent c2bce2e commit e9f7993

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

268/my_solution.js

+37-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1+
// My approach: sort the list and find by comparing with the i.
12
/**
23
* @param {number[]} nums
34
* @return {number}
45
*/
5-
const missingNumber = (nums) => {
6+
const myMissingNumber = (nums) => {
67
// if (1 === nums.length) return !nums[0];
78
console.log(nums);
89
nums.sort((a, b) => (a - b));
@@ -21,10 +22,43 @@ const missingNumber = (nums) => {
2122
return;
2223
}
2324

25+
// Approach 1: XOR
26+
/**
27+
28+
In this approach, we use the fact that XORing a number with itself results in 0. By XORing all the indices and the elements of the input array, and finally XORing the result with the length of the array, the missing number will remain.
29+
30+
This updated code has a time complexity of O(n), as it iterates through the input array once. The space complexity remains O(1) since it does not use any additional data structures that grow with the input size.
31+
32+
* @param {number[]} nums
33+
* @return {number}
34+
*/
35+
const missingNumber1 = (nums) => {
36+
let missing = nums.length;
37+
38+
for (let i = 0; i < nums.length; i++) {
39+
console.log(`i:${i} ^ nums[i]:${nums[i]} ^ missing:${missing}`)
40+
missing ^= i ^ nums[i];
41+
console.log(`missing:${missing}`)
42+
}
43+
console.log(`FINAL missing:${missing}`)
44+
45+
return missing;
46+
}
47+
48+
// Approach 2: Sum(length) - Sum(nums) = missing number
49+
/**
50+
* @param {number[]} nums
51+
* @return {number}
52+
*/
53+
const missingNumber = (nums) => {
54+
return Array.from({ length: nums.length }, (_, index) => index + 1).reduce((a, b) => a + b) - nums.reduce((a, b) => a + b);
55+
}
56+
57+
2458
// missingNumber([3, 0, 1]) // 2
2559
// missingNumber([0, 1]) // 2
2660
// missingNumber([9, 6, 4, 2, 3, 5, 7, 0, 1]) // 8
2761
// missingNumber([1]) // 0
28-
missingNumber([0, 1]) // 2
62+
// missingNumber([0, 1]) // 2
2963
// missingNumber([1, 2]) // 0
30-
missingNumber([45, 35, 38, 13, 12, 23, 48, 15, 44, 21, 43, 26, 6, 37, 1, 19, 22, 3, 11, 32, 4, 16, 28, 49, 29, 36, 33, 8, 9, 39, 46, 17, 41, 7, 2, 5, 27, 20, 40, 34, 30, 25, 47, 0, 31, 42, 24, 10, 14]);
64+
missingNumber([45, 35, 38, 13, 12, 23, 48, 15, 44, 21, 43, 26, 6, 37, 1, 19, 22, 3, 11, 32, 4, 16, 28, 49, 29, 36, 33, 8, 9, 39, 46, 17, 41, 7, 2, 5, 27, 20, 40, 34, 30, 25, 47, 0, 31, 42, 24, 10, 14]); // 18

268/o_solution.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
const missingNumber = (nums) => {
6+
let missing = nums.length;
7+
8+
for (let i = 0; i < nums.length; i++) {
9+
missing ^= i ^ nums[i];
10+
}
11+
12+
return missing;
13+
}

0 commit comments

Comments
 (0)