4. Identify the error in this C code snippet that tries to find the unique element using XOR:
int arr[] = {1, 2, 1, 3, 2};
int result = arr[0];
for(int i = 1; i <= 5; i++) {
result ^= arr[i];
}
printf("%d", result);
medium
A. Loop condition should be < 5, not <= 5
B. Initialize result to 0 instead of arr[0]
C. Use & operator instead of ^
D. Array size is incorrect
Solution
Step 1: Check loop bounds
Array has 5 elements indexed 0 to 4; loop runs i from 1 to 5 inclusive, causing out-of-bounds access at i=5.
Step 2: Correct loop condition
Change loop to i < 5 to avoid accessing arr[5] which is invalid.
Final Answer:
Loop condition should be < 5, not <= 5 -> Option A
Quick Check:
Array index out of bounds fixed by i < 5 [OK]
Hint: Loop till i < array size, not <= [OK]
Common Mistakes:
Using <= instead of < in loop
Ignoring array bounds
Wrong operator used
5. Given an array where every element repeats twice except one element which repeats thrice, can XOR alone find the unique element? If not, what is the correct approach?
hard
A. Yes; XOR works for any repetition count
B. No; use bit counting and modulo 3 to find the unique element
C. No; use sum of elements minus sum of unique elements
D. Yes; XOR twice and then XOR thrice elements
Solution
Step 1: Understand XOR limitation
XOR works only when duplicates appear exactly twice; it fails if duplicates appear thrice.
Step 2: Use bit counting method
Count bits in all numbers, take modulo 3 of each bit count to isolate the unique element's bits.
Final Answer:
No; use bit counting and modulo 3 to find the unique element -> Option B
Quick Check:
XOR fails if duplicates appear thrice; bit count works [OK]
Hint: XOR only works for duplicates twice; use bit count mod 3 otherwise [OK]
Common Mistakes:
Assuming XOR works for any duplicate count
Trying to XOR thrice duplicates
Ignoring bit counting approach
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.