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
36 changes: 36 additions & 0 deletions MinStack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class MinStack {

private int[] stack;
private int[] minStack;
private int top;

public MinStack() {
stack = new int[30000];
minStack = new int[30000];
top = -1;
}

public void push(int val) {
stack[++top] = val;

if (top == 0) {
minStack[top] = val;
} else {
minStack[top] = Math.min(val, minStack[top - 1]);
}
}

public void pop() {
minStack[top] = Integer.MAX_VALUE;
stack[top] = Integer.MAX_VALUE;
top--;
}

public int top() {
return stack[top];
}

public int getMin() {
return minStack[top];
}
}
53 changes: 53 additions & 0 deletions MyHashSet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
class MyHashSet {

private static final int HASH_SIZE = 78727; // Chose a very large prime number
private static final int BUCKET_SIZE = 70; // Each bucket size

private int[][] buckets;
private int[] bucketCount;

public MyHashSet() {
buckets = new int[HASH_SIZE][BUCKET_SIZE];
bucketCount = new int[HASH_SIZE];
}

private int hash(int key) {
return key % HASH_SIZE;
}

public void add(int key) {
int h = hash(key);

// check if exists
for (int i = 0; i < bucketCount[h]; i++) {
if (buckets[h][i] == key) return;
}

// insert if space available
if (bucketCount[h] < BUCKET_SIZE) {
buckets[h][bucketCount[h]] = key;
bucketCount[h]++;
}
// if no space space available not inserted but we know 0 <= key <= 10^6
}

public void remove(int key) {
int h = hash(key);

for (int i = 0; i < bucketCount[h]; i++) {
if (buckets[h][i] == key) {
buckets[h][i] = -1;
bucketCount[h]--;
return;
}
}
}

public boolean contains(int key) {
int h = hash(key);
for (int i = 0; i < bucketCount[h]; i++) {
if (buckets[h][i] == key) return true;
}
return false;
}
}