Bit Manipulation: Lonely Integer

  • + 1 comment

    Simply having "Bit Manipulation" in the title was a good hint. My first thought was to keep a count of each number seen in a hashtable, then loop through the hashtable and print the item that only had 1 for a count. That's O(n) for time complexity, but O(n) for storage. The bitwise solution goes down to O(1) for storage.

    Here's my solution in Python 2:

    def lonely_integer(a):
        result = 0
        for element in a:
            result ^= element
    
        return result
    
    
    n = int(raw_input().strip())
    a = map(int, raw_input().strip().split(' '))
    print lonely_integer(a)