New to coding! Why would I exceed time limit here?
Anonymous User
120

Hello!
I am doing the 2nd coding problem under HashTable/Map Learn section.

Basically, they would call the code as such :

myHashMap.put(1, 1); // The map is now [[1,1]]
myHashMap.put(2, 2); // The map is now [[1,1], [2,2]]
myHashMap.get(1);    // return 1, The map is now [[1,1], [2,2]]
myHashMap.get(3);    // return -1 (i.e., not found), The map is now [[1,1], [2,2]]
myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)
myHashMap.get(2);    // return 1, The map is now [[1,1], [2,1]]
myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]
myHashMap.get(2);    // return -1 (i.e., not found), The map is now [[1,1]]

I found my code to pass a lot of test cases, but it seems to fail when the number of inputs gets really really really large, and I get "Time Exceeded". Can anyone help me why? I'm assuming it's just inefficiency? I don't think I have any infinite loops...

class MyHashMap {
    
    private LinkedList<Bucket> hashMap;

    /** Initialize your data structure here. */
    public MyHashMap() {
        hashMap = new LinkedList<>();
    }
    
    /** value will always be non-negative. */
    public void put(int key, int value) {
        if(get(key) == -1){ //If it doesn't exist
            hashMap.add(new Bucket(key, value));
        } else { //key already exists
            remove(key);
            hashMap.add(new Bucket(key, value));
        }
        print();
    }
    
    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    public int get(int key) {
        for (int i = 0; i < hashMap.size(); i++) {
            if((hashMap.get(i)).contains(key)){
                return hashMap.get(i).value;
            }
        }
        print();
        return -1;
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    
    public void remove(int key) { //This is assuming we already checked it exists
        for (int i = 0; i < hashMap.size(); i++) {
            if((hashMap.get(i)).contains(key)){
                hashMap.remove(i);
            }
        }
        print();
    }
    
    public void print() {
        for (int i = 0; i < hashMap.size(); i++) {
            System.out.print("[" + hashMap.get(i).key + ", " + hashMap.get(i).value + "]");
        }
        System.out.println("");
    }
    
}

class Bucket {
    
    public int key;
    public int value;
    
    public Bucket(int key, int value){
        this.key = key;
        this.value = value;
    }
    
    public boolean contains(int key){
        if(this.key == key){
            return true;
        } else {
            return false;
        }
    }
}
Comments (1)