Documentation Index
Fetch the complete documentation index at: https://mintlify.com/ucxinstructor/dsa_package/llms.txt
Use this file to discover all available pages before exploring further.
Overview
TheHashSet class provides a set data structure that stores unique elements. It is implemented using the HashTable class internally and provides O(1) average-case performance for insertions, deletions, and membership tests.
Constructor
The initial capacity of the underlying hash table
Methods
add
Add an item to the set. If the item already exists, this operation has no effect.The item to add to the set
remove
Remove an item from the set.The item to remove from the set
KeyError if the item is not found in the set
contains
Check if an item is in the set.The item to check for
True if the item is in the set, False otherwiseto_list
Convert the hash set to a list.A list containing all items in the set
Class Methods
from_list
Construct a hash set from an iterable.An optional iterable of initial elements
A new HashSet instance containing the elements from the iterable
Special Methods
__len__
Get the number of items in the set.__contains__
Check if an item is in the set using thein operator.
__iter__
Iterate over the items in the set.__eq__
Check if two sets are equal.__repr__
Get a string representation of the set.Complete Example
Performance
-
Average Case:
- Add: O(1)
- Remove: O(1)
- Contains: O(1)
-
Worst Case:
- Add: O(n)
- Remove: O(n)
- Contains: O(n)
Notes
- The HashSet internally uses a
HashTableto store items - All items are stored as keys in the underlying hashtable with
Trueas the value - The set does not maintain insertion order
- Items must be hashable (the
HashTableconverts them to strings for hashing) - The capacity parameter controls the initial size of the underlying hashtable
- When creating from an iterable, the capacity is automatically set to
len(iterable) * 2for better performance