Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Implement A Hash Map (Main Thread)

Here is the interview question prompt, presented for reference.

Arrays are amazing for looking up elements at specific indices as all elements in memory are contiguous, allowing for O(1) or constant time lookups. But often we don't, or can't, perform lookups via indices. Hash maps and hash tables are a way around this, enabling us to lookup via keys instead.

Can you implement the Map class from scratch? Only two methods are necessary-- get and set. Many programming languages have a built-in hash or dictionary primitive (like Javascript Objects and {} notation), but we don't want to use that for this exercise.

Note: Regular Javascript objects and the Map class are both simple key-value hash tables/associative arrays, with a few key differences:

A Map object can iterate through its elements in insertion order, whereas JavaScript's Objects don't guarantee order. In addition, Objects have default keys due to their prototype, and Maps don't come with default keys. Here's a good breakdown of the two. For the purpose of this exercise, let's assume the same functionality for both.

For the two methods you'll define:

  1. get(key: string) should be given a key, and return the value for that key.
  2. set(key: string, val: string) should take a key and a value as parameters, and store the pair.

Additionally, we've supplied the below hashing function hashStr. It tries to avoid collision, but is not perfect. It takes in a string value and returns an integer.

function hashStr(str) {
    let finalHash = 0;
    for (let i = 0; i < str.length; i++) {
        const charCode = str.charCodeAt(i);
        finalHash += charCode;
    }
    return finalHash;
}

console.log(hashStr('testKey'))
def hashStr(key):
    result = 5381
    for char in key:
        result = 33 * result + ord(char)
    return result

print(hashStr("testKey"))
public class Main {
  public static int hashStr(String str) {
    int finalHash = 0;
    for (int i = 0; i < str.length(); i++) {
      char charCode = str.charAt(i);
      finalHash += (int) charCode;
    }
    return finalHash;
  }

  public static void main(String[] args) {
    System.out.println(hashStr("testKey"));
  }
}

Let's call our new class the Hashmap class, and use it like such:

const m = new Hashmap();
m.set('name', 'Jake');
console.log(m.get('name'));
m = Hashmap()
m.set('name', 'Jake')
print(m.get('name'))
import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap<String, String> m = new HashMap<>();
    m.put("name", "Jake");
    System.out.println(m.get("name"));
  }
}

Constraints

  • Sum of lengths of the string <= 10000
  • The string will consist of ASCII characters
  • Expected time complexity for inserting a key,value pair and retrieving a value : O(1)
  • Expected space complexity : O(n)

You can see the full challenge with visuals at this link.

Challenges • Asked almost 5 years ago by Jake from AlgoDaily

Jake from AlgoDaily Commented on Jul 09, 2019:

This is the main discussion thread generated for Implement A Hash Map.

Jake from AlgoDaily Commented on Jul 09, 2019:

Thanks again @mattvanwinkle:disqus, there was a syntax error in one of the tests.

It seems to be working fine now!

I'll be sure to write some automated tests to ensure the rest of the test cases work :-)

Mohit Commented on Jul 06, 2021:

In python:

solution of the set part looks wrong, as there is no test case which is going for else so it works.

else:
listatindex = self.storage[index]
if p not in listatindex:
self.storage[index] = [p]
self.size += 1
else:
for i in self.storage[index]:
if i == p:
i.value = val
break

Luci Commented on Jan 24, 2022:

In the Javascript sandbox there is an error in the tests.

The line that says assert.isUndefined creates an error message that it is not a function, and won't trigger the lesson end.

Should be assert.equal(dict.get('jake'), undefined);
... as written at the end in the "our final solution" section.

Jake from AlgoDaily Commented on Jan 24, 2022:

Thanks Luci, this is fixed!