Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions HashSet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
//approach used is double hashing
//took two arrays one primary and one secondary
//imlemented hash functions to use in add, remove and contains methods with time complexity of O(1)
class MyHashSet {

private boolean storage[][];
private int buckets; //length of primary array
private int bucketItems;// length of secondary array

private int hash1(int key){
return key%buckets;
}

private int hash2(int key){
return key/bucketItems;
}

public MyHashSet() {
this.buckets=1000;
this.bucketItems=1000;
this.storage=new boolean[buckets][];
}

public void add(int key) { //O(1)
int bucket=hash1(key);
if(storage[bucket]==null){
if(bucket==0){
storage[bucket]= new boolean[bucketItems+1];
}
else{
storage[bucket]= new boolean[bucketItems];
}
}
int bucketItem= hash2(key);
storage[bucket][bucketItem]=true;

}

public void remove(int key) { //O(1)
int bucket=hash1(key);
if(storage[bucket]==null){
return;
}
int bucketItem= hash2(key);
storage[bucket][bucketItem]=false;
}

public boolean contains(int key) { //O(1)
int bucket=hash1(key);
int bucketItem= hash2(key);
if(storage[bucket]==null) return false;
return storage[bucket][bucketItem];


}
}

/**
* Your MyHashSet object will be instantiated and called as such:
* MyHashSet obj = new MyHashSet();
* obj.add(key);
* obj.remove(key);
* boolean param_3 = obj.contains(key);
*/
49 changes: 49 additions & 0 deletions MinStack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//Approach was to have a helper stack called minStack
//Store minimum values in that stack
//while pushing values in normal stack, we will cpmare values in minStack and then store at the top

class MinStack {

Stack <Integer> stack;
Stack <Integer> minStack;
public MinStack() {
stack= new Stack<>();
minStack= new Stack<>();
}

public void push(int val) {
//pushes val to normal stack
stack.push(val);
//we will only push values in minStack if it is empty or value is less than already stored value in minStack
if (minStack.isEmpty() || val<=minStack.peek()){
minStack.push(val);
}

}

public void pop() {
//during pop, we will pop from both stacks
int poppedValue= stack.pop();

if(poppedValue==minStack.peek()){
minStack.pop();
}
}

public int top() {
return stack.peek();
}

public int getMin() {
return minStack.peek();
}
}

/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/