Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Design a HashSet

Hash Mapseasy

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 122: Sets

Design a set of integers. Implement `MyHashSet`: - `add(key)` inserts the key. - `remove(key)` deletes the key if present. - `contains(key)` returns whether the key is present.

Examples

Input: add(1), add(2), contains(1), contains(3), add(2), remove(2), contains(2)
Output: [true, false, false]
contains(1) true, contains(3) false; after remove(2), contains(2) is false.

Sample tests

Input: add/contains/remove
Output: [true,false,false]
Input: remove missing is safe
Output: false

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Removing a missing key should be a safe no-op.

Learning resources

  • MDN: Set
Approach & explanation (try first)

Backing the set with a Set gives O(1) average membership operations.

Loading...
⌘/Ctrl + Enter

Run your code to see results.