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
53 changes: 53 additions & 0 deletions MinStack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Time Complexity : O(1)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

//Description:
// - Store all values in the main stack.
// - Store the minimum value seen so far at each corresponding position in a second stack.
// - When popping, the top of the min stack automatically reveals the minimum for the remaining elements.

class MinStack {
private final Stack<Integer> stack1;
private final Stack<Integer> stack2;
private int min;

public MinStack() {
this.stack1 = new Stack<>();
this.stack2 = new Stack<>();
this.min = Integer.MAX_VALUE;
}

public void push(int value) {
stack1.push(value);
this.min = Math.min(min, value);
stack2.push(this.min);
}

public void pop() {
if(stack1.isEmpty()) {
return;
}

stack1.pop();
stack2.pop();
if(stack2.isEmpty()) {
this.min = Integer.MAX_VALUE;
} else {
this.min = stack2.peek();
}
}

public int top() {
if(stack1.isEmpty()) {
return -1;
}

return stack1.peek();
}

public int getMin() {
return this.min;
}
}
62 changes: 62 additions & 0 deletions MyHashSet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Time Complexity : O(1)
// Space Complexity : O(k), where k is the max key range. ie: O(10^6)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

//Description:
// - Use a 2D boolean array where the first hash selects a bucket and the second hash selects an index within that bucket.
// - Allocate sub-buckets lazily to avoid creating space for all possible keys upfront.

class MyHashSet {

private static final int BUCKET_SIZE = 1000;
private static final int SUB_BUCKET_SIZE = 1000;

private final boolean[][] buckets;

public MyHashSet() {
this.buckets = new boolean[this.BUCKET_SIZE][];
}

public void add(int key) {
int hash1 = hash1(key);
if(buckets[hash1] == null) {
int subBucketSize = this.SUB_BUCKET_SIZE;
if(hash1 == 0) {
subBucketSize += 1;
}
buckets[hash1] = new boolean[subBucketSize];
}
int hash2 = hash2(key);
buckets[hash1][hash2] = true;
}

public void remove(int key) {
int hash1 = hash1(key);
if(buckets[hash1] == null) {
return;
}
int hash2 = hash2(key);

buckets[hash1][hash2] = false;
}

public boolean contains(int key) {
int hash1 = hash1(key);
if(buckets[hash1] == null) {
return false;
}

int hash2 = hash2(key);

return buckets[hash1][hash2];
}

private int hash1(int key) {
return key % this.BUCKET_SIZE;
}

private int hash2(int key) {
return key / this.BUCKET_SIZE;
}
}