Lonely Integer

Sort by

recency

|

901 Discussions

|

  • + 0 comments

    Simply XOR should solve this problem with just O(n) time complexity and O(1) space complexity.

    num = 0 for i in a: num ^=i return num

  • + 0 comments

    Py solution :

    def lonelyinteger(a):
        # Write your code here
        for i in set(a):
            if a.count(i) == 1:
                return i
    
  • + 0 comments

    Here is a solution with C# public static int lonelyinteger(List a) { Dictionary myDict = new Dictionary(a.Count); int result = 0; for(int i = 0; i < a.Count; i++){ if(myDict.ContainsKey(a[i])){ myDict[a[i]] += 1; }else{ myDict.Add(a[i], 1); } } foreach(KeyValuePair item in myDict ){ Console.WriteLine(item.Value+ " "); if(item.Value == 1){ result = item.Key; break; } } return result; }

    }

  • + 0 comments

    I wish I had thought of the mathematical approach.

  • + 0 comments
    def lonelyinteger(a): 
        # Write your code here
        
        count_dict = {} # Initialize an empty dictionary
        for item in a:
            if item in count_dict:
                count_dict[item] += 1  
                # Increment the count if item is already in dictionary
            else:
                count_dict[item] = 1   
                # Add the item with count 1 if it's not in the dictionary
        return [key for key, value in count_dict.items() if value == 1]
        
        
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        n = int(input().strip())
    
        a = list(map(int, input().rstrip().split()))
    
        result = lonelyinteger(a)
    
        fptr.write(' '.join(map(str,result)) + '\n')
    
        fptr.close()