Hash Set is a data structure that stores unique elements using a hash function for fast access.
Key Characteristics:
Hash Function: A hash function converts input elements into array indices. It takes an element of any size and produces a fixed-size integer that determines where the element will be stored. A good hash function should distribute elements uniformly across the set to minimize collisions.
Hash Calculation Example: For string "apple" with set size 7:
Step 1: Sum ASCII values: a(97) + p(112) + p(112) + l(108) + e(101) = 530
Step 2: Apply modulo: 530 % 7 = 5
Therefore, hash("apple") = 5, so "apple" is stored in bucket 5.
Operation | Average | Worst |
---|---|---|
Add | O(1) | O(n) |
Contains | O(1) | O(n) |
Remove | O(1) | O(n) |
Component | Space |
---|---|
Set Storage | O(n) |
Chain Storage | O(k) |