A hash set stores unique elements with O(1) average time for add, remove, and lookup operations. Use it when you only care about existence, not associated values.
Basic Operations
Set Operations
Common Use Cases
Detecting Duplicates
Finding Intersection
Tracking Visited States
Finding Missing/Extra Elements
Longest Consecutive Sequence
A classic set problem: find the length of the longest consecutive sequence in O(n) time.
Time Complexity Reference
Operation
Average
Worst
Add
O(1)
O(n)*
Remove
O(1)
O(n)*
Lookup (in)
O(1)
O(n)*
Iteration
O(n)
O(n)
Union
O(m + n)
O(m + n)
Intersection
O(min(m, n))
O(m * n)*
*Worst case O(n) occurs with hash collisions. In practice with good hash functions, this is rare.
Common Interview Tips
O(1) membership testing: Replace O(n) list lookups with O(1) set lookups when checking if an element exists.
Sequence start trick: For consecutive sequence problems, only start counting from elements where n-1 is not in the set.
Deduplication: Converting a list to a set instantly removes all duplicates.