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.
- Lonely Integer
- Discussions
Lonely Integer
Lonely Integer
Sort by
recency
|
936 Discussions
|
Please Login in order to post a comment
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.
def lonelyinteger(a): unique = 0 for num in a: unique ^= num return unique
My Java 8 Solution:
c# linq
return a.Select(x=>x).Where(y=>a.Where(x=>x == y).Count() == 1).First();