Function to find a duplicate element in a limited range list code example
Example: Function to find a duplicate element in a limited range list
def findDuplicate(A):
xor = 0
# take xor of all list elements
for i in range(len(A)):
xor ^= A[i]
# take xor of numbers from 1 to `n-1`
for i in range(1, len(A)):
xor ^= i
# same elements will cancel each other as a ^ a = 0,
# 0 ^ 0 = 0 and a ^ 0 = a
# `xor` will contain the missing number
return xor