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
84 changes: 84 additions & 0 deletions HasMap.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
class MyHashMap {
// Entry class to store key-value pairs
private static class Entry {
int key;
int value;
Entry next;

Entry(int key, int value) {
this.key = key;
this.value = value;
}
}

private static final int SIZE = 1000; // Number of buckets
private Entry[] buckets;

public MyHashMap() {
buckets = new Entry[SIZE];
}

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

public void put(int key, int value) {
int index = hash(key);
Entry head = buckets[index];

if (head == null) {
buckets[index] = new Entry(key, value);
return;
}

Entry curr = head;
while (curr != null) {
if (curr.key == key) {
curr.value = value; // Update value if key exists
return;
}
if (curr.next == null) break;
curr = curr.next;
}

// Append new entry at the end of the chain
curr.next = new Entry(key, value);
}

public int get(int key) {
int index = hash(key);
Entry curr = buckets[index];

while (curr != null) {
if (curr.key == key) {
return curr.value;
}
curr = curr.next;
}

return -1; // Key not found
}

public void remove(int key) {
int index = hash(key);
Entry curr = buckets[index];
Entry prev = null;

while (curr != null) {
if (curr.key == key) {
if (prev == null) {
// Remove head of list
buckets[index] = curr.next;
} else {
prev.next = curr.next;
}
return;
}
prev = curr;
curr = curr.next;
}
}
}

//Time Complexity : O(1)
//Space Complexity : O(n)
46 changes: 46 additions & 0 deletions Stack(Queue).java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import java.util.Stack;

class MyQueue {
private Stack<Integer> stackIn;
private Stack<Integer> stackOut;

public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}

public void push(int x) {
stackIn.push(x);
}

public int pop() {
transferIfNeeded();
return stackOut.pop();
}

public int peek() {
transferIfNeeded();
return stackOut.peek();
}

public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}

private void transferIfNeeded() {
if (stackOut.isEmpty()) {
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
}
}


//Time complexity : push(x) → O(1)

pop() → Amortized O(1)

peek() → Amortized O(1)

empty() → O(1)