Last active
August 29, 2015 14:17
-
-
Save rakeshsukla53/4a957bd2bc969336347a to your computer and use it in GitHub Desktop.
Find single elements among duplicates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = [7, 2, 2, 3, 3, 4, 4, 55, 55, 100, 100] | |
b = 0 | |
#for i in range(len(a)): | |
#you will find the forever alone element in the array | |
def XOR(): | |
global b | |
for num in a: #use XOR to iterate over the do the solution | |
print "b = %d" %b | |
print "num = %d" %num #o(n) complexity | |
b ^= num | |
print "result = %d" %b | |
print '\n' | |
XOR() | |
Logic | |
A number xor'd with itself is 0. So the first time you see a value and xor it, it sets the bits and the second time you see it it flips the bits back. So the one that wasn't in a pair never gets flipped back and you end up with that number. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment