Leetcode 705: Design HashSet

grid47
grid47
Exploring patterns and algorithms
Aug 28, 2024 9 min read

A set of elements where the hashset design is highlighted, with each element glowing softly in its unique location.
Solution to LeetCode 705: Design HashSet Problem

Design a custom HashSet without using any built-in hash table libraries. Implement the MyHashSet class with methods to add, remove, and check the existence of a value.
Problem
Approach
Steps
Complexity
Input: You are given a set of operations to perform on a custom HashSet. The operations are: add, remove, and contains, each involving a key (an integer).
Example: Input: ["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"] [[], [1], [2], [1], [3], [2], [2], [2], [2]]
Constraints:
• 0 <= key <= 10^6
• At most 10^4 operations will be made on the HashSet.
Output: The function should return the results of the operations. If the operation is add or remove, return null. If the operation is contains, return a boolean value (true or false).
Example: Output: [null, null, null, true, false, null, true, null, false]
Constraints:
• The set should handle both insertion and deletion operations efficiently.
Goal: Design a HashSet that efficiently supports the add, remove, and contains operations using a custom approach.
Steps:
• 1. Create a HashSet using an array of linked lists (or other structure) to store values.
• 2. Implement the add function to insert a value into the HashSet if it doesn't already exist.
• 3. Implement the remove function to remove a value if it exists in the HashSet.
• 4. Implement the contains function to check if a value exists in the HashSet.
Goal: The HashSet should handle multiple operations efficiently, ideally in O(1) time for each operation.
Steps:
• The size of the HashSet should be dynamic enough to accommodate the key range of 0 to 10^6.
• The solution must handle up to 10^4 operations.
Assumptions:
• The keys in the HashSet are integers within the specified range.
• The operations are done in sequence, and the set is empty at the start.
Input: Input: ["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"] [[], [1], [2], [1], [3], [2], [2], [2], [2]]
Explanation: In this example, we first add 1 and 2 to the HashSet. We check if 1 is present (it is), then check for 3 (it isn't). Adding 2 again doesn't change the set, checking for 2 shows it is present, removing 2 removes it from the set, and checking for 2 afterward shows it isn't present.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus