4. Identify the error in the following code snippet that attempts to find two non-repeating elements using XOR:
const arr = [4, 1, 2, 1, 2, 5];
let xor = 0;
for (let i = 0; i <= arr.length; i++) {
xor ^= arr[i];
}
console.log(xor);
medium
A. Use let xor = null instead of 0
B. Loop condition should be i < arr.length, not i <= arr.length
C. Array elements should be sorted before XOR
D. XOR should start from 1, not 0
Solution
Step 1: Check loop boundary condition
The loop runs from i=0 to i<=arr.length, which accesses arr[arr.length] (undefined).
Step 2: Correct loop condition
Change condition to i < arr.length to avoid accessing undefined and runtime error.
Final Answer:
Loop condition should be i < arr.length, not i <= arr.length -> Option B
Quick Check:
Loop must stay within array bounds [OK]
Hint: Use i < arr.length to avoid out-of-bounds errors [OK]
Common Mistakes:
Using <= instead of < in loop
Starting XOR with 1 instead of 0
Sorting array unnecessarily
5. Given the array [6, 1, 3, 6, 1, 5], which two numbers are the non-repeating elements found using the XOR method? Choose the correct pair.
hard
A. [3, 5]
B. [6, 1]
C. [1, 3]
D. [5, 6]
Solution
Step 1: XOR all elements to get xor of two unique numbers
6^1=7, 7^3=4, 4^6=2, 2^1=3, 3^5=6 (xor = 6).
Step 2: Find rightmost set bit and separate elements
Rightmost set bit in 6 (binary 110) is bit 2 (value 2). Separate elements into two groups based on this bit and XOR each group to find unique numbers 3 and 5.
Final Answer:
[3, 5] -> Option A
Quick Check:
Unique elements are 3 and 5 [OK]
Hint: Use rightmost set bit to split and find unique numbers [OK]
Common Mistakes:
Mixing up repeating and unique elements
Not splitting array by set bit
Incorrect XOR calculations
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.