Set and Dictionary complexity. Advantage over Array?
The gist
Set is an unordered collection of unique elements; Dictionary holds key–value pairs with unique keys. Both are hash tables, hence:
- Lookup (
contains,subscript), insertion, removal — O(1) on average. - Worst case — O(n) (all keys in one bucket), which in practice doesn't happen thanks to SipHash with a random seed.
- Iteration — O(n), order is undefined and changes between runs.
- Growing the table (rehash) — O(n), but amortized;
reserveCapacityavoids it. - Set operations (
union,intersection,subtracting) — O(n + m).
A Set element and a Dictionary key must be Hashable; the dictionary value can be anything.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep