Given a list of numbers we like to find the first Non Repeating number.
Example:
{ 1,1,2,3,3,4,5,8,9,2,4,7,5 } Ans = 8
Solution:
We can use a dictionary data structure to collect similar items in a single bucket and we update the count of repeated items as a value to the dictionary
So the dictionary we are going to build would look like (a(i), frequency(a(i))
[1,2]
[2,2]
[3,2]
[4,2]
[5,2]
[8,1]
[9,1]
So the first non repeated number would be 8 as every other number before it has a frequency of 2 (repeated two times).
public int FirstNonRepeating(int [] nums) {
Dictionary<int,int> dict = new Dictionary<int,int>();
int nonrepeat = 0;
for(int i=0; i < nums.Length; i++) {
if (!dict.ContainsKey(nums[i]))
dict.Add(nums[i], 1);
else
dict[nums[i]]++;
}
foreach(int item in dict.Keys) {
if (dict[item] == 1)
return item;
}
return nonrepeat;
}