I just wanted to check whether there contains any duplicates in my array. I searched on Google and see some approaches:
let containsDuplicates = Set(array).count != array.count
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.