Lonely Integer

Sort by

recency

|

936 Discussions

|

  • + 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.

  • + 0 comments

    def lonelyinteger(a): unique = 0 for num in a: unique ^= num return unique

  • + 0 comments
    from collections import Counter as c
    
    def lonelyinteger(a):
        b = c(a)
        r = [i for i,j in b.items() if j == 1]
        return print(*r)
    
    if __name__ == '__main__':
        n = int(input().strip())
        a = list(map(int, input().rstrip().split()))
        lonelyinteger(a)
    
  • + 0 comments

    My Java 8 Solution:

    public static int lonelyinteger(List<Integer> a) {
            Set<Integer> set = new HashSet<>();
            for (int number : a) {
                boolean isAdded = set.add(number);
                if (!isAdded) {
                    set.remove(number);
                }
            }
            
            return set.iterator().next();
        }
    
  • + 0 comments

    c# linq

    return a.Select(x=>x).Where(y=>a.Where(x=>x == y).Count() == 1).First();