DEV Community

Calvin
Calvin

Posted on

Leetcode:'Contains Duplicates' 🤔 🤔

The Leetcode contains duplicates problem requires one to write a program that returns true if there are duplicates in an array and false if every element in the array is distinct.

Solution:


  if nums.uniq.length == nums.length
        return false
    else
        return true
    end

Enter fullscreen mode Exit fullscreen mode

Video Walkthrough

Top comments (2)

Collapse
 
brbb profile image
Francesco

I wouldn't solve it this way, imagine to do it without built-in functions, like on a whiteboard. If you are doing it for job interviews, the recruiters are most probably looking for a scanning of the array, some smart data structure which automatically excludes duplicate keys and maybe something you can extend.
For example you can initialise a Set from the array and check the length of the original array and the keys stored in the set, which in case of duplicates will be shorter (sets allow unique keys only).

Another way is scanning the array and adding key by key to a set and return false if the key is already present. This last way is ideal if the follow-up to this question is: count all the duplicates.

Just few examples, hope it can help!

Collapse
 
calvinoea profile image
Calvin

Thanks a lot, Francesco. I'll try and solve it using different approaches, including the ones you mentioned.