HackerRank ‘Lonely Integer’ Solution

H
Short Problem Definition:

There are N integers in an array A. All but one integer occur in pairs. Your task is to find out the number that occurs only once.

Link

Lonely Integer

Complexity:

time complexity is O(N);

space complexity is O(1)

Execution:

XORing two equal numbers cancels them out. XOR all numbers together.

Solution:
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/py
def lonelyinteger(a):
    answer = 0
    for candidate in a:
        answer ^= candidate
    return answer
if __name__ == '__main__':
    a = input()
    b = map(int, raw_input().strip().split(" "))
    print lonelyinteger(b)

About the author

Add comment

Archives

Categories