Check for Duplicate Values in Array Algo

By   Tewodros   Date Posted: Oct. 12, 2021  Hits: 874   Category:  Algorithm   Total Comment: 0             A+ A-


side

Check for Duplicate Values in Array containing random number which are repeating or distinct. Our job is to tell if the array contains repeating elements. 

Example:  3, 4, 8, 6, 7, 9, 4, 77  Ans = True. 4 appears twice

Example:  3, 8, 6, 7, 9, 4, 77  Ans = False. No dups

Solution:

We loop through the array one element at a time and we throw it in to a hashset if we didn't do this before. But if we already visit this number before, then we can check it in the set and quickly tell the list has distinct elements or not. 

  public bool ContainsDuplicate(int[] nums) {       

       HashSet<int> hs = new HashSet<int>();       

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

           if(!hs.Contains(nums[i]))

               hs.Add(nums[i]);

           else

               return true;

       }       

       return false;

   }


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

Back to Top