Find all DUPLICATE VALUES IN ARRAY ALGO

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


side

Find all duplicate values in Array containing random number which are repeating or distinct. 

Example:  3, 4, 8, 6, 7, 9, 4,3, 77  Ans = {4, 3}

Example:  3, 8, 6, 7, 9, 4, 77  Ans = {}

Solution:

We loop through the array one element at a time and we throw it in to a hashtable if we didn't do this before. But if we already add it to the hashtable , then we found the answer and we add it to our result array or list.

 

           public IList<int> solution(int[] A)      {

               IList<int> ans = new List<int>();

               Hashtable ht = new Hashtable();

 

               for(int i=0; i< A.Length; i++)       {

                   if (!ht.ContainsKey(A[i]))

                       ht[A[i]] = A[i];

                   else      {

                       ans.Add(A[i]);

                   }

               }

               return ans;

           }


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:* kpaxlb

Back to Top