Lonely Integer

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