File: design-hashmap/solution.py

Date: 2026-06-06

Time: 16:18

Purpose

This file implements LeetCode problem 706 - Design HashMap. It provides a from-scratch hash map (dictionary) without using any built-in hash table libraries. The class MyHashMap supports put, get, and remove — the three core operations of an associative array. It's a data structure design problem that tests understanding of hashing and collision resolution.

Key Components

MyHashMap

A hash map backed by a fixed-size array of buckets, using separate chaining for collision resolution.

Constants

Patterns

Separate chaining: Each bucket is an independent list. Colliding keys coexist in the same bucket as separate entries. This is the simplest collision resolution strategy — no probing, no rehashing, no tombstones.

Mutable pair lists: Pairs are stored as [key, value] (mutable lists, not tuples), which lets put do pair[1] = value to update in place without removing and re-inserting.

No dynamic resizing: The bucket count is fixed at construction. This is acceptable under LeetCode's constraint of at most 10^4 operations — the average chain length stays well under 10.

Dependencies

Imports: None. The implementation is self-contained with no standard library or third-party imports.

Imported by: design-hashmap/testsolution.py directly, and the "Imported By" list in the prompt shows hundreds of test files — this is an artifact of the repo's test infrastructure pattern, not a real dependency. Only testsolution.py in this directory actually exercises MyHashMap.

Flow

1. Constructor creates 1009 empty lists.

2. On put(key, value): hash the key → get the bucket → linear scan for existing key → update or append.

3. On get(key): hash → scan → return value or -1.

4. On remove(key): hash → scan with enumeratepop(i) on match.

All three operations touch exactly one bucket. The work per operation is O(n/1009) amortized, where n is the number of stored keys.

Invariants

Error Handling

There is none. The code assumes all inputs are valid integers within LeetCode's constraints (0 <= key, value <= 10^6). get and remove on missing keys silently return -1 or no-op, respectively — no exceptions are raised.

Topics to Explore

Beliefs