Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Design a HashMap

Hash Mapsmedium

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 124: Maps: Fundamentals

Design a key-value store without using any built-in hash-map library directly in the public API. Implement the `MyHashMap` class: - `put(key, value)` inserts or updates the value for `key`. - `get(key)` returns the value for `key`, or `-1` if it is not present. - `remove(key)` deletes the mapping for `key` if it exists.

Examples

Input: put(1,1), put(2,2), get(1), get(3), put(2,1), get(2), remove(2), get(2)
Output: [1, -1, 1, -1]
get(1) is 1, get(3) is -1 (absent). After put(2,1), get(2) is 1. After remove(2), get(2) is -1.

Sample tests

Input: put/get/remove sequence
Output: [1,-1,1,-1]
Input: put then get
Output: 100

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Returning undefined instead of -1 for missing keys.
  • Using `key in obj` style checks can be fooled by inherited properties; a Map avoids that.

Learning resources

  • MDN: Map
Approach & explanation (try first)

Backing the API with a Map gives O(1) average put/get/remove. get checks presence before returning so absent keys yield -1.

Loading...
⌘/Ctrl + Enter

Run your code to see results.