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

// Approach:
// Use two-level indexing with primary and secondary hashing.
// Store values in a 2D array and use -1 to represent missing keys.

class MyHashMap {
int primaryBuckets;
int secondaryBuckets;
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 primaryIndex = getPrimaryHash(key);

if (storage[primaryIndex] == null) {
if (primaryIndex == 0) {
storage[primaryIndex] = new int[secondaryBuckets + 1];
} else {
storage[primaryIndex] = new int[secondaryBuckets];
}

for (int i = 0; i < storage[primaryIndex].length; i++) {
storage[primaryIndex][i] = -1;
}
}

int secondaryIndex = getSecondaryHash(key);
storage[primaryIndex][secondaryIndex] = value;
}

public int get(int key) {
int primaryIndex = getPrimaryHash(key);
if (storage[primaryIndex] == null) {
return -1;
}

int secondaryIndex = getSecondaryHash(key);
return storage[primaryIndex][secondaryIndex];
}

public void remove(int key) {
int primaryIndex = getPrimaryHash(key);
if (storage[primaryIndex] == null) {
return;
}

int secondaryIndex = getSecondaryHash(key);
storage[primaryIndex][secondaryIndex] = -1;
}
}
48 changes: 48 additions & 0 deletions MyQueue.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Time Complexity : O(1)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No


// Approach:
// Use one stack for push operations and another for pop/peek.
// Transfer elements only when needed to maintain FIFO order.


import java.util.Stack;

class MyQueue {
Stack<Integer> inputStack;
Stack<Integer> outputStack;

public MyQueue() {
this.inputStack = new Stack<>();
this.outputStack = new Stack<>();
}

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

public int pop() {
if (outputStack.isEmpty()) {
while (!inputStack.isEmpty()) {
outputStack.push(inputStack.pop());
}
}
return outputStack.pop();
}

public int peek() {
if (outputStack.isEmpty()) {
while (!inputStack.isEmpty()) {
outputStack.push(inputStack.pop());
}
}
return outputStack.peek();
}

public boolean empty() {
return inputStack.isEmpty() && outputStack.isEmpty();
}
}