Sweeper Sweeper - 2 years ago 56
Swift Question

Is this approach to check duplicates in an array relatively efficient? Why or why not?

I just wanted to check whether there contains any duplicates in my array. I searched on Google and see some approaches:

  • Double for-loop loops though the array and comparing each item

  • Creating a dictionary that stores the number of occurrences of each item

But these methods require a lot of loops and I'm kind of lazy to write a large amount of code just for this functionality. xD.

So I thought of this creative way:

let containsDuplicates = Set(array).count != array.count

However, is this method faster or slower than the other two? I'm not sure because it seems to create a set which I think needs to loop through the array. And I don't know whether accessing the
also loops through the whole array.

If I only have at most 50 items in the array, will this even matter?

Answer Source

That's pretty much the best way. Dictionary storage is constant time, and each item only needs to be stored once, so it's an O(n) solution, vs the O(n^2) for the double for-loop approach. The space efficiency is lower, but that's usually not a concern these days.

If you're doing this often, I would suggest using some kind of hybrid data structure, so that you're not constantly generating these Sets from scratch.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download