Daily iOS
CS fundamentals and algorithms

HashMap vs Set

In a one-hour coding test you have to find duplicates in a list of customer IDs and also count how often each ID appears. When would you use Swift's Set and when Dictionary?

How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

For duplicate detection, where you only need to know whether you've seen it, insert into a Set and catch the moment inserted comes back false; when each key needs a value, like a count, use a Dictionary keyed by id with counts[id, default: 0] += 1. Both insert and look up in average O(1), so one pass is O(n).

Share a question