Problem 706

Abstract / Summary

Design a map that supports adding key value pairs and retrieving values quickly using keys.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0706.py

class MyHashMap:
    MOD = 1023

    def hash(self, key):
        return key % self.MOD

    def __init__(self):
        self.data = []
        for _ in range(self.MOD):
            self.data.append( [] )

    def put(self, key: int, value: int) -> None:
        bucket = self.hash(key)
        if self.data[bucket]:
            for i, item in enumerate(self.data[bucket]):
                if item[0] == key:
                    self.data[bucket][i] = ( key, value )
                    return
        self.data[bucket].append(( key, value ))

    def get(self, key: int) -> int:
        bucket = self.hash(key)
        if self.data[bucket]:
            for i, item in enumerate(self.data[bucket]):
                if item[0] == key:
                    return item[1]
        return -1

    def remove(self, key: int) -> None:
        bucket = self.hash(key)
        if self.data[bucket]:
            for i, item in enumerate(self.data[bucket]):
                if item[0] == key:
                    del self.data[bucket][i]
                    break
35 lines | 1088 bytes | submitted October 4, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 67% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Design
  • Hash Function
  • Hash Table
  • Linked List
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a simple hash map for integer keys and values. It relies on an array of buckets, each bucket being a Python list that stores key-value pairs as two-element tuples. The class supplies three public operations-put, get, and remove-that correspond to insertion, lookup, and deletion. A fixed modulus determines the number of buckets, and a straightforward modulo operation serves as the hash function.

Hash Function

def hash(self, key):
    return key % self.MOD

The hash function maps any integer key to an index in the range [0, MOD-1]. By using the remainder operator, the function guarantees that the resulting bucket index is always valid for the underlying array. This deterministic mapping ensures that the same key always resolves to the same bucket, which is essential for correct retrieval and removal.

Initialization

def __init__(self):
    self.data = []
    for _ in range(self.MOD):
        self.data.append([])

During construction, the class creates a list named data that contains MOD empty sub-lists. Each sub-list represents a bucket that will hold the key-value tuples that hash to its index. The explicit loop populates the outer list with distinct list objects, preventing accidental sharing of bucket references.

Put Operation

def put(self, key: int, value: int) -> None:
    bucket = self.hash(key)
    if self.data[bucket]:
        for i, item in enumerate(self.data[bucket]):
            if item[0] == key:
                self.data[bucket][i] = (key, value)
                return
    self.data[bucket].append((key, value))

The put method first computes the target bucket. If the bucket already contains entries, it iterates through them to locate an existing tuple with a matching key. Upon finding such a tuple, the method replaces the entire entry with a new (key, value) pair, effectively updating the stored value. If no matching key is found, the method appends a new tuple to the bucket, thereby handling the insertion of a previously unseen key.

Get Operation

def get(self, key: int) -> int:
    bucket = self.hash(key)
    if self.data[bucket]:
        for i, item in enumerate(self.data[bucket]):
            if item[0] == key:
                return item[1]
    return -1

The get method also begins by locating the appropriate bucket. It then scans the bucket for a tuple whose first element equals the requested key. When a match is discovered, the method returns the associated value. If the bucket is empty or the key is absent, the method returns -1, providing a sentinel value that signals a missing entry.

Remove Operation

def remove(self, key: int) -> None:
    bucket = self.hash(key)
    if self.data[bucket]:
        for i, item in enumerate(self.data[bucket]):
            if item[0] == key:
                del self.data[bucket][i]
                break

The remove method follows the same bucket-selection logic. It iterates over the bucket’s contents, and upon locating a tuple with the target key, it deletes that tuple from the list using the del statement. The loop terminates immediately after removal, ensuring that only the first matching entry is eliminated, which aligns with the invariant that each key appears at most once per bucket.

Edge Cases

The implementation gracefully handles several edge conditions. When a bucket is empty, the if self.data[bucket]: guard prevents unnecessary iteration, allowing get to return the sentinel -1 and remove to exit without error. The put method’s early return after an update avoids adding duplicate entries for the same key, preserving the one-to-one mapping between keys and values. The remove method’s break statement ensures that the loop stops after the targeted tuple is deleted, preventing accidental removal of subsequent entries that might share the same key (which cannot happen under normal usage but is still a safe guard). The use of modulo arithmetic in the hash function also correctly handles negative keys, as Python’s % operator yields a non-negative remainder, thereby mapping any integer key to a valid bucket index.

Performance Optimizations

A notable optimization is the fixed-size bucket array determined by MOD = 1023. By preallocating the exact number of buckets, the implementation avoids dynamic resizing of the outer list, which could incur costly reallocation and copying operations. The choice of a prime-like number for MOD (1023 is close to a power of two but not a power itself) helps distribute keys more uniformly across buckets, reducing the likelihood of long chains in any single bucket. Within each bucket, the code updates an existing entry in place rather than removing and re-appending, which minimizes list mutation overhead. The early-exit patterns in put, get, and remove-returning immediately after a match is found-prevent unnecessary traversal of the remainder of the bucket, yielding faster average-case behavior when keys are located near the front of the list. Finally, the use of tuple assignment (key, value) for updates leverages Python’s immutable tuple creation, which is generally faster than constructing a custom object for each entry.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big wall with many numbered mailboxes. This code is like a special worker who manages all those boxes. First, there is a rule called hash that looks at a key, like a locker number, and decides which box it belongs in by finding the remainder when dividing.

The init part sets up the wall by creating a long line of empty boxes so everything has a place to go. When putting something away, the code figures out the right box number, looks inside that box to see if the item is already there, and updates it if it finds a match. If not, it just slips the new item into the box.

When looking for something, the code finds the correct box again and checks every item inside until it discovers the one that matches the secret code. If it reaches the end and finds nothing, it knows the item is missing. Removing is similar because the code goes to the right box, scans the items, and if it finds the one requested, it takes it out of the box and throws it away.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.26 | σ = 1.07

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java
leetcode.ca C++ Java Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
Dijkstra-Edu Java
everthis JS
fartem Ruby
fpdjsns C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
qiyuangong Java
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
Dijkstra-Edu Java
everthis JavaScript
fartem Ruby
fpdjsns C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
qiyuangong Java
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
36 links | 24 authors | 9 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

5 easy 1 medium
7 solutions   October 4, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality