Twitter | Phone screen | Linear probing hash table
Anonymous User
2149

Build a linear probing hash table. Got a rejection for this. This is what I had built and it seemed to work for a fix bucket size. Is there anything wrong in this?

// Linear probing hash table
// 0 - 10000
// put(1, 1) => 0 => {key: 1, value: 1}
// put(1, 2) =>  
// put(2, 2) => 0 => 1 => 2 => {key : 2, value: 2} 

class HashMap{
    constructor() {
        this.bucketSize = 3;
        this.hashMap = new Array(this.bucketSize).fill(undefined);
    }
    
    getHashIndex(key) {
        return key % this.bucketSize;
    }
    
    put(key, val) {
        const hashIndex = this.getHashIndex(key);
        if (this.hashMap[hashIndex]) {
            // we are in a collision
            // search for the next empty bucket/hashIndex
            let i = hashIndex;
            let limitBucketSize = this.bucketSize;
            while (i < limitBucketSize) {
                if (this.hashMap[i] === undefined) {
                    // found an empty bucket/hashIndex
                    this.hashMap[i] = {};
                    this.hashMap[i][key] = val;
                    break;
                }
                i += 1; 
                if (i === this.bucketSize) {
                    i = i % this.bucketSize;
                    limitBucketSize = hashIndex;
                }
            }
        } else {
            this.hashMap[hashIndex] = {};
            this.hashMap[hashIndex][key] = val;
        }
    }
    
    get(key) {
        const hashIndex = this.getHashIndex(key);
        console.log(this.hashMap);
        let i = hashIndex;
        let limitBucketSize = this.bucketSize;
        while (i < limitBucketSize) {
            if (this.hashMap[i] !== undefined) {
                // found the key we are looking for
                if (this.hashMap[i][key]) {
                    return this.hashMap[i][key];
                }
            }
            i += 1; 
            if (i === this.bucketSize) {
                i = i % this.bucketSize;
                limitBucketSize = hashIndex;
            }
        }
        return null;
    }
}

const hm = new HashMap();
hm.put(1, 1); // bucketSize 1
hm.put(2, 2);  // bucketSize 2
console.log(hm.get(1));
hm.put(3, 3);  // bucketSize 3
console.log(hm.get(1));
Comments (6)