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


// Your code here along with comments explaining your approach
class MyHashMap {

class Node{
int key, val;
Node next;

public Node(int key, int val){
this.key = key;
this.val = val;
}
}

private Node[] storage;

public MyHashMap() {
this.storage = new Node[10000];
}

public int hash(int key){
return key%10000;
}

public Node find(Node head, int key){
Node prev = null;
Node curr = head;
while(curr != null && curr.key != key){
prev = curr;
curr = curr.next;
}

return prev;
}

public void put(int key, int value) {
int idx = hash(key);
if(storage [idx] == null){
storage[idx] = new Node(-1,-1);
}

Node prev = find(storage[idx], key);
if(prev.next !=null){
prev.next.val = value;
}else{
prev.next = new Node(key,value);
}
}

public int get(int key) {
int idx = hash(key);
if(storage[idx] == null) return -1;
Node prev = find(storage[idx], key);

if(prev.next !=null){
return prev.next.val;
}

return -1;
}

public void remove(int key) {
int idx = hash(key);
if(storage[idx] == null){
return;
}
Node prev = find(storage[idx], key);
if(prev.next == null){
return;
}
prev.next = prev.next.next;
}
}

55 changes: 55 additions & 0 deletions MyQueue.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Time Complexity : O(1) average
// Space Complexity :O(n)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : No

class MyQueue {

Stack<Integer> in;
Stack<Integer> out;
public MyQueue() {
in = new Stack<>();
out = new Stack<>();
}

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

public int pop() {
if(out.isEmpty()){
while(!in.isEmpty()){
out.push(in.pop());
}
}
return out.pop();
}

public int peek() {
if(out.isEmpty()){
while(!in.isEmpty()){
out.push(in.pop());
}
}

return out.peek();
}

public boolean empty() {

if(in.isEmpty() && out.isEmpty()){
return true;
}

return false;
}
}

/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
7 changes: 0 additions & 7 deletions Sample.java

This file was deleted.