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

import java.util.ArrayList;
import java.util.List;

public class HashSet {
private static final int MAX_SIZE = 1000;
private final List<Integer>[] set = new List[MAX_SIZE];

HashSet() {}

public void add(Integer value) {
if (contains(value)) {
return;
}
int position = hashFunction(value);
List<Integer> valuesAtPosition = set[position];
if (valuesAtPosition == null) {
set[position] = new ArrayList<>();
}
set[position].add(value);
}

public void remove(Integer value) {
if (contains(value)) {
int position = hashFunction(value);
List<Integer> valuesAtPosition = set[position];
valuesAtPosition.remove(value);
}
}

public boolean contains(Integer value) {
int position = hashFunction(value);
if (set[position] == null || set[position].isEmpty()) return false;
for (Integer currentValue : set[position]) {
if (currentValue.equals(value)) return true;
}
return false;
}

private int hashFunction(Integer value) {
return value % MAX_SIZE;
}

}
52 changes: 52 additions & 0 deletions MinStack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Time Complexity : O(1) for all operations
// Space Complexity : O(N) in worst case, if inputs are sorted in descending order. The minstack will hold N values.
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

import java.util.Stack;

public class MinStack {
//Keep 2 stacks, one to keep all values
Stack<Integer> stack = new Stack<>();
//In other one, push new value if it smaller than the current top value in the stack
Stack<Integer> minValues = new Stack<>();

MinStack() {
}

void push(int val) {
stack.push(val);
if (minValues.isEmpty() || minValues.peek() >= val) {
minValues.push(val);
}
}

void pop() {
if (stack.isEmpty()) {
System.out.println("Stack is Empty");
}

if (stack.peek().equals(minValues.peek())) {
stack.pop();
minValues.pop();
} else {
stack.pop();
}
}

int top() {
if (stack.isEmpty()) {
System.out.println("Stack is Empty");
return -1;
}
return stack.peek();
}

int getMin() {
if (stack.isEmpty() || minValues.isEmpty()) {
System.out.println("Stack is Empty");
return -1;
}
return minValues.peek();
}
}