A hash set stores unique values and supports fast membership checks in typical cases. In Python, the built-in set is the standard hash set.
Sets are useful when the algorithm only needs to know whether a value has appeared, not what value is attached to it.
Core Idea
A set answers membership questions directly: “Have I seen this before?” or “Is this value allowed?”
Typical add, remove, and membership operations are treated as O(1) average time.
Python Example
seen = set()
for value in [4, 7, 4, 9]:
if value in seen:
print("duplicate", value)
seen.add(value)The second 4 is detected because 4 is already in seen.
Common Confusions
A set does not store duplicates. Adding the same value again does not create another copy.
A set is not a list without order. If the algorithm depends on sequence position, use a list or store the position separately.
When To Use It
Use a hash set for duplicate detection, visited nodes, allowed values, forbidden values, and fast membership checks.