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

//Time Complexity O(1)
//Space Complexity O(n)

public class MyHashMap {

private final int primaryBuckets;
private final int secondaryBuckets;
private final int[][] storage;

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

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

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

public void put(int key, int value) {
int p = getPrimaryHash(key);
if (storage[p] == null) {
int length = (p == 0) ? secondaryBuckets + 1 : secondaryBuckets;
storage[p] = new int[length];
for (int i = 0; i < length; i++) storage[p][i] = -1;
}
int s = getSecondaryHash(key);
storage[p][s] = value;
}

public int get(int key) {
int p = getPrimaryHash(key);
int[] bucket = storage[p];
if (bucket == null) return -1;
int s = getSecondaryHash(key);
return bucket[s];
}

public void remove(int key) {
int p = getPrimaryHash(key);
int[] bucket = storage[p];
if (bucket == null) return;
int s = getSecondaryHash(key);
bucket[s] = -1;
}
}
44 changes: 44 additions & 0 deletions MyQueue.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
//Time Complexity O(1), for pop it would O(n) worst case
//Space Complexity O(n)
class MyQueue() {

private val s1 = java.util.Stack<Int>()
private val s2 = java.util.Stack<Int>()
fun push(x: Int) {
s1.push(x)
}

fun pop(): Int {
if(s2.isEmpty()) {
while(!s1.isEmpty()) {
s2.push(s1.pop())
}
}
return s2.pop()
}

fun peek(): Int {
if(!s2.isEmpty()) {
return s2.peek()
} else {
while(!s1.isEmpty()) {
s2.push(s1.pop())
}
}
return s2.peek()
}

fun empty(): Boolean {
return s1.isEmpty() && s2.isEmpty()
}

}

/**
* Your MyQueue object will be instantiated and called as such:
* var obj = MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/