Lonely Integer

  • + 0 comments

    My Python solution using Mathematical logic:

    def lonelyinteger(a):
        '''
        Mathematical solution
        
        The sum of the elements of a is the sum of the
        doubles of each repeated element, plus the lonely (b)
        sum(a) = sum[2.x] + b
        
        The sum of the unique elements is the sum of all
        the unique elements that are repeated, plus the lonely (b)
        sum(set(a)) = sum[x] + b
        
        Then, 2*sum(set(a)) - sum(a) = b
        
        Time complexity: O(n)
        Space complexity: O(1)
        '''
        
        return 2*sum(set(a)) - sum(a)