Non Repeating Numbers In Python
def singleNumber(nums):
xor_result = 0
# Calculate the XOR of all numbers in the array
for num in nums:
xor_result ^= num
# Find the rightmost set bit in the XOR result
# This helps us partition the numbers into two groups
rightmost_set_bit = 1
while (xor_result & rightmost_set_bit) == 0:
rightmost_set_bit <<= 1
# Initialize two variables to hold the XOR results for each group
group1 = 0
group2 = 0
# Partition the numbers into two groups based on the rightmost set bit
for num in nums:
if num & rightmost_set_bit:
group1 ^= num
else:
group2 ^= num
# Return the two distinct numbers in ascending order
return [min(group1, group2), max(group1, group2)]
Non Repeating Numbers In C#
using System;
using System.Collections.Generic;
class Program
{
static List<int> SingleNumber(int[] nums)
{
int xorResult = 0;
// Calculate the XOR of all numbers in the array
foreach (int num in nums)
{
xorResult ^= num;
}
// Find the rightmost set bit in the XOR result
// This helps us partition the numbers into two groups
int rightmostSetBit = 1;
while ((xorResult & rightmostSetBit) == 0)
{
rightmostSetBit <<= 1;
}
// Initialize two variables to hold the XOR results for each group
int group1 = 0;
int group2 = 0;
// Partition the numbers into two groups based on the rightmost set bit
foreach (int num in nums)
{
if ((num & rightmostSetBit) != 0)
{
group1 ^= num;
}
else
{
group2 ^= num;
}
}
// Return the two distinct numbers in ascending order
return new List<int> { Math.Min(group1, group2), Math.Max(group1, group2) };
}
static void Main(string[] args)
{
int[] nums = { 1, 2, 3, 2, 1, 4 };
List<int> result = SingleNumber(nums);
Console.WriteLine(string.Join(", ", result)); // Output: 3, 4
}
}