The final XOR result is 4, which is the only number appearing once.
Final Answer:
4 -> Option C
Quick Check:
XOR cancels duplicates, leaves 4 [OK]
Hint: XOR duplicates cancel, leftover is unique [OK]
Common Mistakes:
Adding numbers instead of XOR
Miscomputing XOR steps
Ignoring duplicates
4. Identify the error in this Go code snippet that tries to find the only non-repeating element using XOR:
package main
import "fmt"
func main() {
nums := []int{5, 1, 5, 2, 1}
var result int
for i := 0; i <= len(nums); i++ {
result ^= nums[i]
}
fmt.Println(result)
}
medium
A. Loop condition should be i < len(nums), not i <= len(nums)
B. Variable 'result' should be initialized to 1 instead of 0
C. The XOR operator '^=' is invalid in Go
D. The slice 'nums' should be declared as an array
Solution
Step 1: Check loop boundary condition
The loop runs from i=0 to i<=len(nums), which causes out-of-range access at i=len(nums).
Step 2: Correct the loop condition
Change condition to i < len(nums) to avoid index out of range error.
Final Answer:
Loop condition should be i < len(nums), not i <= len(nums) -> Option A
Quick Check:
Index out of range fixed by loop condition [OK]
Hint: Loop index must be less than length, not equal [OK]
Common Mistakes:
Using <= instead of <
Initializing result incorrectly
Misunderstanding XOR operator
5. Given an array where every element appears twice except one element which appears once, how can you find the unique element using XOR in Go? Consider the array nums := []int{7, 9, 7, 8, 9, 10, 10}. What is the unique element?