Tutorialspoint
Problem
Solution
Submissions

HashSet using Array

Certification: Basic Level Accuracy: 0% Submissions: 3 Points: 8

Write a Java program to implement a HashSet data structure using arrays. The implementation should support the following operations: add(key), remove(key), contains(key), and size(). The HashSet should be able to store integers.

Example 1
  • Input: ["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
    [[], [1], [2], [1], [3], [2], [2], [2], [2]]
  • Output: [null, null, null, true, false, null, true, null, false]
  • Explanation:
        
    • MyHashSet myHashSet = new MyHashSet(); 
    • myHashSet.add(1); // set = [1]  
    • myHashSet.add(2); // set = [1, 2]  
    • myHashSet.contains(1); // return True
    • myHashSet.contains(3); // return False, (not found) 
    • myHashSet.add(2); // set = [1, 2]  
    • myHashSet.contains(2); // return True
    • myHashSet.remove(2); // set = [1] 
    • myHashSet.contains(2); // return False, (already removed)
Example 2
  • Input: ["MyHashSet", "add", "remove", "add", "contains", "contains", "add", "remove", "contains", "size"]
    [[], [10], [10], [20], [10], [20], [30], [20], [20], []]
  • Output: [null, null, null, null, false, true, null, null, false, 2]
  • Explanation: Various operations are performed on the hash set, and the final size is 2.
Constraints
  • 0 ≤ key ≤ 10^6
  • At most 10^4 calls will be made to add, remove, contains, and size
  • Time Complexity: O(1) average case for all operations
  • Space Complexity: O(n) where n is the capacity of the hash set
HashSetArraysD. E. ShawOracle
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use an array of boolean values or a linked list array to implement the hash set
  • Implement a hash function to map keys to array indices
  • Handle collisions using a technique like chaining or open addressing
  • For simplicity, you can use modulo operation for hashing
  • Consider resizing the array when the load factor exceeds a threshold

Steps to solve by this approach:

 Step 1: Create an array of ArrayList to handle collisions (chaining approach).
 Step 2: Implement a hash function that maps a key to an index in the array.
 Step 3: For add operation, check if the key already exists to avoid duplicates.
 Step 4: For remove operation, find the key in the appropriate bucket and remove it.
 Step 5: For contains operation, check if the key exists in its corresponding bucket.
 Step 6: Keep track of the size by incrementing when adding and decrementing when removing.
 Step 7: Return the correct size when the size method is called.

Submitted Code :