Skip to content

Commit f79beac

Browse files
committed
Update remove method to trigger a resize if load factor falls below 0.25
1 parent 86ff19d commit f79beac

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

src/dataStructures/hashSet/openAddressing/HashSet.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ public HashSet() {
5151
/**
5252
* Adds the specified element to this set if it is not already present
5353
* If this set already contains the element, the call leaves the set unchanged and returns false.
54+
* <p> If load factor (0.75) is exceeded, triggers a resize operation and double the current capacity.
5455
*
5556
* @param element the element to be added to this set
5657
* @return true if this set did not already contain the specified
@@ -77,11 +78,18 @@ public boolean add(T element) {
7778
*<p>
7879
* Removed elements are replaced with a Tombstone instead of NULL. This is to prevent search from terminating earlier
7980
* than expected when looking for an element.
81+
* <p>
82+
* If load factor falls below 0.25, trigger a resize and halve the current capacity.
8083
*
8184
* @param element the element to be removed from this set, if present
8285
* @return true if this set contained the specified element
8386
*/
8487
public boolean remove(T element) {
88+
// If load factor falls below 0.25 and still above minimum size (16), shrink the hashset by half.
89+
if (this.size() <= this.capacity() * 0.25 && this.capacity() / 2 >= INITIAL_CAPACITY) {
90+
resize(this.capacity() / 2);
91+
}
92+
8593
int bucketIndex = this.search(element);
8694
if (bucketIndex == ELEMENT_NOT_FOUND) {
8795
return false; // If the index returned by the probe function contains an empty bucket, then the element is not present in the set.

0 commit comments

Comments
 (0)