diff --git a/MyHashSet.java b/MyHashSet.java new file mode 100644 index 00000000..7378b7f4 --- /dev/null +++ b/MyHashSet.java @@ -0,0 +1,45 @@ +//Design a Hash Set - Double Hashing Solution +//Time Complexity : O(1) +//Space Complexity : O(n) + +public class MyHashSet { + boolean[][] set; + int pbucket; + int sbucket; + + public MyHashSet() { + this.pbucket = 1000; + this.sbucket = 1000; + this.set = new boolean[pbucket][]; + } + + public void add(int key) { + int hash1 = key%pbucket; + if(set[hash1] == null) { + //initiate the array + if(hash1 == 0) + set[hash1] = new boolean[sbucket+1]; + else + set[hash1] = new boolean[sbucket]; + } + int hash2 = key/sbucket; + set[hash1][hash2] = true; + } + + public void remove(int key) { + int hash1 = key%pbucket; + if(set[hash1] != null) { + int hash2 = key/sbucket; + set[hash1][hash2] = false; + } + } + + public boolean contains(int key) { + int hash1 = key%pbucket; + if(set[hash1] == null) { + return false; + } + int hash2 = key/sbucket; + return set[hash1][hash2]; + } +} diff --git a/MyQueue.java b/MyQueue.java new file mode 100644 index 00000000..25181dbd --- /dev/null +++ b/MyQueue.java @@ -0,0 +1,39 @@ +//Implement Queue using Stacks +//Time Complexity: O(1) for push, O(n) for pop and peek in worst case, O(1) for pop and peek Amortized +//Space Complexity: O(n) + +import java.util.Stack; + +class MyQueue { + + Stack in; + Stack out; + + public MyQueue() { + in = new Stack<>(); + out = new Stack<>(); + } + + public void push(int x) { + in.push(x); + } + + public int pop() { + if(empty()) return -1; + peek(); + return out.pop(); + } + + public int peek() { + if(out.isEmpty()) { + while(!in.isEmpty()) { + out.push(in.pop()); + } + } + return out.peek(); + } + + public boolean empty() { + return in.isEmpty() && out.isEmpty(); + } +}