3 ms·
In Java this prints -4 int [] nums = { 2, -2, 0, 0 }; int dup = findDupe(nums); System.out.println("dup="+dup);
by ape4 11y ago
In Java this prints -4
int [] nums = { 2, -2, 0, 0 };
int dup = findDupe(nums);
System.out.println("dup="+dup);
- ammon 11y agoThis only works if the numbers are in a known range (say sequential from 1 to 100), and you XOR in the index (plus 1) as well. Then each number is XOR'd two times, except the duplicate, which is XOR'd 3 times (and thus remains at the end). The fact that the code is wrong shows why this question is a very bad interview question. EDIT The given code works to find the only non-duplicate item in a list (perhaps that was what was intended)
- eranation 11y agoyes,that was the intention, I can't edit by now. I had to leave fast and then got "noprocast" on and couldn't reply / correct but it is nice that people got what I said through the lines! it should have been called findNonDupe and the var should have been called nonDup. Hope I'll do better in a real interview ;)
- cema 11y agoThe problem was formulated as to find the only non-duplicate number.
- eranation 11y agoYes, my wife was waiting on me for lunch so I made tons of typos, yes I meant find the only non duplicate number. and I meant O(1) memory O(N) time complexity.