Lonely Integer

Sort by

recency

|

940 Discussions

|

  • + 0 comments

    JAVA

    for(Integer n: a){ int frec = Collections.frequency(a, n); if(frec==1){ num=n; } } return num;

  • + 0 comments

    Scala Solution

    def lonelyinteger(a: Array[Int]): Int = {
        // Write your code here)
            a.reduce(_^_)
        }
    
  • + 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)
    
  • + 0 comments

    group the numbers find the group that has only one element first .Single gets the IGrouping second .Single gets the int from that Grouping.

    return a.GroupBy(i => i).Where(i => i.Count() ==1).Single().Single();
    
  • + 0 comments

    Lonely Integer (C# Solution)


    ✅ C# Solution using XOR (Efficient and Clean)

    `csharp using System; using System.Collections.Generic; using System.Linq;

    class Result { // XOR-based solution: all duplicates cancel out public static int lonelyinteger(List a) { int result = 0; foreach (int num in a) { result ^= num; } return result; } }

    class Solution { public static void Main(string[] args) { int n = Convert.ToInt32(Console.ReadLine().Trim());

        List<int> a = Console.ReadLine()
                             .Trim()
                             .Split(' ')
                             .Select(int.Parse)
                             .ToList();
    
        int result = Result.lonelyinteger(a);
        Console.WriteLine(result);
    }
    

    }

    🔍 Explanation

    We use the bitwise XOR (^) operator because:

    • x ^ x = 0 (duplicate elements cancel each other)
    • x ^ 0 = x

    Since every element except one appears twice, XOR-ing all elements leaves the unique one.

    ⏱️ Time and Space Complexity Time Complexity: O(n) – Single loop through the list.

    Space Complexity: O(1) – No additional data structures needed.