Set (Hash-based)

A set implementation that uses a hash table to keep track of the unique elements.

Pros Cons
Best amortized times for inserts/deletes Bad hashing implementations or sizing can lead to linear times
No ordering of elements
Implementations
Python: set

s = set()
s.add(10) # {10}
s.add(20) # {10, 20}
s.add(10) # {10}

s.remove(10) # {20}

Java: Set

Set<Integer> s = new HashSet<>();
s.add(10); // {10}
s.add(20); // {10, 20}
s.add(10); // {10, 20}

s.remove(10); // {20}

C++: unordered_set

std:: unordered_set <int> s;

s.insert(10); // {10}
s.insert(20): // {10, 20}
s.insert(10); // {10, 20}

s.erase(10); // {20}

Operations Worst Average
DeleteO(n)O(1)
InsertO(n)O(1)
SearchO(n)O(1)

Similar