Challenge - 5 Problems
XOR Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of the XOR-based function?
Consider the following JavaScript function that finds the only non-repeating element in an array where every other element repeats twice. What will be the output when the function is called with the given input?
DSA Javascript
function findNonRepeating(arr) {
let result = 0;
for (let num of arr) {
result ^= num;
}
return result;
}
console.log(findNonRepeating([2, 3, 5, 4, 5, 3, 4]));Attempts:
2 left
💡 Hint
XOR of a number with itself is zero, and XOR with zero is the number itself.
✗ Incorrect
The function XORs all numbers. Pairs cancel out because n ^ n = 0. The only non-repeating number remains.
❓ Predict Output
intermediateWhat is the output when the array has negative numbers?
What will the following code print when the input array contains negative and positive numbers?
DSA Javascript
function findNonRepeating(arr) {
let result = 0;
for (let num of arr) {
result ^= num;
}
return result;
}
console.log(findNonRepeating([-1, 2, -1, 3, 2]));Attempts:
2 left
💡 Hint
XOR works with negative numbers as well.
✗ Incorrect
Pairs cancel out, leaving 3 as the only non-repeating element.
🔧 Debug
advancedIdentify the error in this XOR implementation
The following code is intended to find the only non-repeating element using XOR. What will be the output when run?
DSA Javascript
function findNonRepeating(arr) {
let result = 0;
for (let i = 0; i <= arr.length; i++) {
result ^= arr[i];
}
return result;
}
console.log(findNonRepeating([1, 1, 2]));Attempts:
2 left
💡 Hint
Check the loop boundary condition carefully.
✗ Incorrect
The loop runs one step too far, accessing arr[arr.length] which is undefined. XORing with undefined results in NaN.
❓ Predict Output
advancedWhat is the output of XOR on an empty array?
What will the following code print when the input array is empty?
DSA Javascript
function findNonRepeating(arr) {
let result = 0;
for (let num of arr) {
result ^= num;
}
return result;
}
console.log(findNonRepeating([]));Attempts:
2 left
💡 Hint
XOR with zero and no numbers returns zero.
✗ Incorrect
No elements to XOR, so result remains 0 and is returned.
❓ Predict Output
expertWhat is the output of XOR on a large array with one unique element?
Given the array where every number except one appears twice, what will the following code print?
DSA Javascript
function findNonRepeating(arr) {
let result = 0;
for (let num of arr) {
result ^= num;
}
return result;
}
const arr = [];
for(let i = 1; i <= 1000; i++) {
arr.push(i);
arr.push(i);
}
arr.push(12345);
console.log(findNonRepeating(arr));Attempts:
2 left
💡 Hint
All pairs cancel out, leaving the unique number.
✗ Incorrect
All numbers from 1 to 1000 appear twice and cancel out, leaving 12345.
