Design HashMap

Easy · Arrays & Hashing · Array · Hash Table · Linked List · Design · Hash Function

Problem

Build your own hash map without using any built-in hash table library.

Implement MyHashMap:

The tests call the class through a list of operation names and a list of their arguments; each call's return value is collected, with None for the constructor and the void methods.

Examples

Input: ops = ["MyHashMap","put","put","get","put","get","remove","get"], args = [[],[7,70],[1016,5],[7],[7,71],[7],[1016],[1016]]
Output: [null,null,null,70,null,71,null,-1]

Keys 7 and 1016 land in the same bucket of 1009 but are kept apart; putting 7 again overwrites 70 with 71.

Input: ops = ["MyHashMap","get","put","get"], args = [[],[0],[0,0],[0]]
Output: [null,-1,null,0]

A missing key returns -1, while a stored value of 0 is returned as 0.

Input: ops = ["MyHashMap","put","put","remove","get","get","put","get"], args = [[],[1,10],[2,20],[1],[1],[2],[1,11],[1]]
Output: [null,null,null,null,-1,20,null,11]

After key 1 is removed, get(1) is -1 until it is put again; key 2 is untouched.

Constraints

Approaches

Follow-up

What if the number of keys were not known in advance? Track the load factor (keys per bucket) and, when it passes about 0.75, double the bucket array and re-insert every pair: each put is still O(1) amortized. And since keys here are at most 10^6, a plain array of 10^6 + 1 values with -1 for "absent" also works, trading memory for simplicity.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…