We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
`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.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Lonely Integer
You are viewing a single comment's thread. Return to all 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());
}
🔍 Explanation
We use the bitwise XOR (^) operator because:
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.