Find the Missing Number with Bitwise Operators - JavaScript

preview_player
Показать описание
Using XOR bitwise operator to solve this coding problem

#softwareengineering #javascript #shorts

Music:
Creative Commons / Attribution 4.0 International (CC BY 4.0)
Рекомендации по теме
Комментарии
Автор

n(n+1)/2 give sum of numbers 0 to n
n(n+1)/2 - (sum of all number in array) = missing Number

cnkumar
Автор

instead of xor you could use (in the loop)
answer = answer + i - nums[i]
and then just use the positive of answer

JasonKaler
Автор

I like this version:
const missingNumber = function(nums) {
const max =
let actual = 0;
for(let i = 0; i < nums.length; i++) {
actual = actual + nums[i];
}
return max - actual;
};

Eumeltier
Автор

I would avoid this solution, based on its lack of readability.

dignum
Автор

1. create a hashmap off the elements in the array
2. loop thru the hashmap, range should be 0 to n and whichever key is found missing is the answer

kkvaruas
Автор

Multiple ways are there
Use case of cyclic sort
Doing sum
Xor

alokpd
Автор

//Solution in C#:
int missingNumber(int[] nums)
{
var expected = Enumerable.Range(0, nums.Length);

var missing =

return missing.FirstOrDefault();
}

//Usage:
int[] { 3, 0, 2, 1, 4, 5, 6, 8 })); // Returns 7

nimalas
Автор

I'm having trouble following why the for loop goes up to nums.length. Won't that cause i to be equal to n and nums[i] to be an index out of bounds?

If the idea is to have xor compare against n at some point. I think initializing xor = n while keeping i < n is a better approach.

calderov
Автор

Or you could just do (nums.length +1).factorial() - sum(nums). No loop required

timhowitz
Автор

Now make the starting number be the smallest integer, let's break it 😂

Although offsetting the xor value could also work

audrianmarak
Автор

Why can't you just sum the entire array and subtract from n(n+1)/2? Simple and easy

bhaveshsinghal
Автор

I thought bitwise XOR literally worked bit by bit. So e.g. 8 ^ 5 == 13 and 3 ^ 3 == 0

RedHair
Автор

1. input_arr.sort()
2. const missing = Array.from({ length: input_arr[input_arr.length - 1] }, (_, index) => index + 1).filter(num => !input_arr.includes(num))[0]

RemoteAccessGG
Автор

Wow. Javascript allows you to xor with undefined (nums[i = nums.length]). Lol. This is so stupid.

vighnesh
Автор

Is there a typo in this code? I think that the initial value assigned to the xor variable should be nums.length. Otherwise you'll never have a chance to cancel out the last index.

Pluvofor
Автор

And what will you do if missed more than one number ?

arthur.v.babayan
Автор

If there are two numbers missing from the array?

JakeKoekemoer
Автор

there is a brand new thing called frequency Array you know !!
also keeps the complexity O(n).
you have to loop twice.
but it's much clearer than this fuckin' logic operators shit

youssefzayn
Автор

How do you even come up with this on your own

igormizyk