A HashSet is a data structure that stores unique elements only and offers O(1) average time complexity for insertion, deletion, and lookup. It’s backed by a hash table just like a Hashmap, but only stores keys, no values.
It’s implemented using the built-in set
type.
# Empty set
s = set()
# With values
s = {1, 2, 3}
s.add(4) # Adds 4
s.add(2) # Already exists, no effect
s.remove(2) # Removes 2 (raises KeyError if not found)
s.discard(5) # Safe remove (no error if 5 not present)
if 3 in s:
print("Exists")
for item in s:
print(item)
len(s) # Number of unique elements
s.clear()
Useful for solving problems involving duplicates, intersections, or differences.
a = {1, 2, 3}
b = {3, 4, 5}
a | b # {1, 2, 3, 4, 5}
a & b # {3}
a - b # {1, 2}
a ^ b # {1, 2, 4, 5}
Solving problems like: