Find the element that appears once where every other element appears twice | GeeksforGeeks

preview_player
Показать описание

This video is contributed by Shubham Kumar

Please Like, Comment and Share the Video among your friends.

Also, Subscribe if you haven't already! :)
Рекомендации по теме
Комментарии
Автор

Could someone actually explain how this works. For example I have an array [1, 2, 2, 1, 3] We are setting the res value to ar[0]. So when the loop starts it compare res = ar[0] to ar[i]. So for example it would compare 1 and 2. Then it will go to then it will compare 1 and 2. Then it will compare 1 and 2. Them will compare 1 and 1 which will return 0? So for the above example how would it isolate 3??

Jechjames
Автор

What about this
sum(set(arr))*2 – sum(arr)

Tensor
Автор

int findSingle(int ar[], int ar_size)
{
// Do XOR of all elements and return
int res = ar[0];
for (int i = 1; i < ar_size; i++)
res = res ^ ar[i];

return res;
}

wecan
Автор

Damn! This seemingly simple question is actually not simple. I wouldn't see the XOR in a million year. And yes I was a digital hardware design before. I'd used XOR for simple checksum and stuff.

LinhHoang-zimt
Автор

May I ask why it requires O(1) extra space? How to calculate it?

BPJennieYeager
Автор

can we sort the array and then see if the adjacent element is == to the selected element

II_xD_II
Автор

But what about if there is more than 1 number which appear exactly once.

SumitKumar-fngj
Автор

What if the non repetiting element is not at the first position in array?

pranavkurkure
Автор

Having looked at the code what would be XOR of a number with a different number

HansNiemann
Автор

It fails when either there are multiple numbers with single occurrence or when the number occurs with odd frequency.

anujjhamb
Автор

its wrong res should not be equal to arr[0]

shivamagarwal