Find First Non Repeating number

By   Tewodros   Date Posted: Dec. 1, 2021  Hits: 944   Category:  Algorithm   Total Comment: 0             A+ A-


side

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;             

           }

 

 

 

 


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* worfau

Back to Top