HackerRank 'Lonely Integer' Solution

Martin Kysel · February 23, 2015

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.

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:

#!/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)

Twitter, Facebook

To learn more about solving Coding Challenges in Python, I recommend these courses: Educative.io Python Algorithms, Educative.io Python Coding Interview.