Challenge - 5 Problems
XOR Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of XOR to find unique element
What is the output of the following Java code that uses XOR to find the only non-repeating element in the array?
DSA Java
public class Main { public static void main(String[] args) { int[] arr = {2, 3, 5, 4, 5, 3, 4}; int result = 0; for (int num : arr) { result ^= num; } System.out.println(result); } }
Attempts:
2 left
💡 Hint
XOR of a number with itself is 0, and XOR with 0 is the number itself.
✗ Incorrect
The XOR operation cancels out all numbers appearing twice, leaving only the unique number. Here, 2 appears once, so the output is 2.
❓ Predict Output
intermediateResult after XOR operations
What will be printed after running this Java code snippet?
DSA Java
int[] nums = {7, 9, 7, 9, 11}; int unique = 0; for (int n : nums) { unique ^= n; } System.out.println(unique);
Attempts:
2 left
💡 Hint
Pairs cancel out with XOR, leaving the unique number.
✗ Incorrect
7 and 9 appear twice and cancel out. 11 appears once, so the output is 11.
🔧 Debug
advancedIdentify the error in XOR unique element code
What error will this Java code produce when trying to find the unique element using XOR?
DSA Java
int[] arr = {1, 2, 1, 3, 2}; int result = 0; for (int num : arr) { result ^= num; } System.out.println(result);
Attempts:
2 left
💡 Hint
Check if all variables are initialized before use.
✗ Incorrect
The variable 'result' was not initialized before XOR operation, causing a compilation error. Initializing it to 0 fixes the error and outputs 3.
🧠 Conceptual
advancedWhy XOR works for finding the unique element?
Why does XOR operation help in finding the only non-repeating element in an array where every other element repeats twice?
Attempts:
2 left
💡 Hint
Think about how pairs cancel out using XOR.
✗ Incorrect
XOR cancels out pairs because n ^ n = 0, and 0 ^ n = n, leaving only the unique element.
❓ Predict Output
expertOutput of XOR with multiple unique elements
What will be the output of this Java code that uses XOR on an array with two unique elements?
DSA Java
int[] arr = {4, 1, 2, 1, 2, 5}; int xorResult = 0; for (int num : arr) { xorResult ^= num; } System.out.println(xorResult);
Attempts:
2 left
💡 Hint
XOR of two different unique numbers is not zero, check carefully.
✗ Incorrect
The array has two unique numbers 4 and 5. XOR of 4 and 5 is 1, and since 1 appears twice, it cancels out, leaving 4 ^ 5 = 1. So output is 1.
