Skip to content

Commit

Permalink
W1:Q3: DesignHashSet
Browse files Browse the repository at this point in the history
  • Loading branch information
Abhishek Surve committed Aug 2, 2020
1 parent a343cdc commit f97f684
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions WEEK1/DesignHashSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,70 @@ public boolean contains(int key) {
* obj.remove(key);
* boolean param_3 = obj.contains(key);
*/


/**
* Solution using Linked List (chaining)
*/
class MyHashSet {

private Bucket[] buckets;
private int keyRange;

/**
* Initialize your data structure here.
*/
public MyHashSet() {
this.keyRange = 769;
this.buckets = new Bucket[this.keyRange];
for (int i = 0; i < this.keyRange; ++i) {
this.buckets[i] = new Bucket();
}
}

protected int _hash(int key) {
return key % this.keyRange;
}

public void add(int key) {
int bucketIndex = _hash(key);
this.buckets[bucketIndex].insert(key);
}

public void remove(int key) {
int bucketIndex = _hash(key);
this.buckets[bucketIndex].delete(key);
}

/**
* Returns true if this set contains the specified element
*/
public boolean contains(int key) {
int bucketIndex = _hash(key);
return this.buckets[bucketIndex].exists(key);
}
}

class Bucket {

private LinkedList<Integer> container;

public Bucket() {
this.container = new LinkedList<Integer>();
}

public void insert(int key) {
int index = this.container.indexOf(key);
if (index == -1) this.container.addFirst(key);
}

public void delete(int key) {
this.container.remove(key);
}

public boolean exists(int key) {
int index = this.container.indexOf(key);
return index != -1;
}
}
}

0 comments on commit f97f684

Please sign in to comment.