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
66 changes: 66 additions & 0 deletions MinStack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Approach:
// The idea is to store current minumum in a min variable, keep track of previous mininums in a seperate stack for every push that happens on the original stack.
// So whenever a pop happens, we check if the popped element is minumum, if so we set the current minumum with the top of minStack, and pop this top element from minStack
// To prevent managing multiple same minimums, we follow this approach otherwise, we can achieve the same without the min variable, but through the minStack itself.


// Time Complexity:

// push(), pop() - O(1)
// top, getMin() - O(1)

// Space complexity:
// push(), pop() - O(1)
// top, getMin() - O(1)

// Code
import java.util.Stack;

class MinStack {

Stack<Integer> st;
Stack<Integer> minSt;
int min;

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


public void push(int value) {
if(min >= value)
{
minSt.push(min);
min = value;
}

st.push(value);
}

public void pop() {
if(min == st.pop())
{
min = minSt.peek();
minSt.pop();
}
}

public int top() {
return st.peek();
}

public int getMin() {
return min;
}
}

/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(value);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
55 changes: 55 additions & 0 deletions MyHashSet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
class MyHashSet {
boolean[][] storage;
int primaryBuckets;
int secondaryBuckets;

public MyHashSet() {
this.primaryBuckets = 1000;
this.secondaryBuckets = 1000;
this.storage = new boolean[primaryBuckets][];
}

private int getPrimaryHash(int key)
{
return key % primaryBuckets;
}

private int getSecondaryHash(int key)
{
return key / secondaryBuckets;
}

public void add(int key)
{
int primaryHash = getPrimaryHash(key);
if(storage[primaryHash] == null){
if(primaryHash == 0) {
storage[primaryHash] = new boolean[secondaryBuckets+1];
}
else{
storage[primaryHash] = new boolean[secondaryBuckets];
}
}
int secondaryHash = getSecondaryHash(key);
storage[primaryHash][secondaryHash] = true;
}

public void remove(int key) {
int primaryHash = getPrimaryHash(key);

if (storage[primaryHash] == null){
return;
}
int secondaryHash = getSecondaryHash(key);
storage[primaryHash][secondaryHash] = false;
}

public boolean contains(int key) {
int primaryHash = getPrimaryHash(key);
if (storage[primaryHash] == null){
return false;
}
int secondaryHash = getSecondaryHash(key);
return storage[primaryHash][secondaryHash];
}
}