Implement a Hash Map (Easy)
Good evening! Here's our prompt for today.
You may see this problem at Autodesk, Instacart, Salesforce, Stripe, Godaddy, Vmware, Adobe, Atlassian, Netflix, Groupon, Square, Tableau Software, Uber, Pivotal, Spotify, Freshworks, Asana, Automattic, Cohesity, C3 Ai, Benchling, and Pagerduty.
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
Object
s 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 Object
s don't guarantee order. In addition, Object
s have default keys due to their prototype, and Map
s 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:
get(key: string)
should be given a key, and return the value for that key.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.
1public class Main {
2 public static int hashStr(String str) {
3 int finalHash = 0;
4 for (int i = 0; i < str.length(); i++) {
5 char charCode = str.charAt(i);
6 finalHash += (int) charCode;
7 }
8 return finalHash;
9 }
10
11 public static void main(String[] args) {
12 System.out.println(hashStr("testKey"));
13 }
14}
Let's call our new class the Hashmap
class, and use it like such:
1import java.util.HashMap;
2
3public class Main {
4 public static void main(String[] args) {
5 HashMap<String, String> m = new HashMap<>();
6 m.put("name", "Jake");
7 System.out.println(m.get("name"));
8 }
9}
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)
xxxxxxxxxx
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import static org.junit.Assert.*;
// solution
class Hashmap {
// fill in
// with solution
public Hashmap() {
// fill in
// with solution
}
public void set(String key, Object val) {
// fill in
// with solution
}
public Object get(String key) {
// fill in
// with solution