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
45 changes: 45 additions & 0 deletions MyHashSet.java
Original file line number Diff line number Diff line change
@@ -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];
}
}
39 changes: 39 additions & 0 deletions MyQueue.java
Original file line number Diff line number Diff line change
@@ -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<Integer> in;
Stack<Integer> 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();
}
}