How to find the stray number in a list?
How to find the one different value using C#?
1 min readMar 31, 2023
Here’s the CodeWars exercise:
You are given an odd-length array of integers, in which all of them are the same, except for one single number.
Complete the method which accepts such an array, and returns that single different number.
The input array will always be valid! (odd-length >= 3)
Examples
[1, 1, 2] ==> 2
[17, 17, 3, 17, 17, 17, 17] ==> 3
I’m thinking more about using an intermediate Dictionary to keep track of the number.
using System.Collections.Generic;
class Solution
{
public static int Stray(int[] numbers)
{
var numberCountDict = new Dictionary<int, int>();
foreach (var number in numbers)
{
if (numberCountDict.ContainsKey(number))
{
numberCountDict[number]++;
}
else {
numberCountDict.Add(number, 1);
}
}
var finalNumber = 0;
foreach(KeyValuePair<int, int> entry in numberCountDict)
{
if (entry.Value.Equals(1))
{
finalNumber = entry.Key;
}
}
return finalNumber;
}
}