Design Hashset in swift

[Question]: Design a HashSet without using any built-in hash table libraries.

Implement MyHashSet class:

  • void add(key) Inserts the value key into the HashSet.
  • bool contains(key) Returns whether the value key exists in the HashSet or not.
  • void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.
class MyHashSet {
     private var data = [Bool?](repeating: false, count: 1000001)
     init() {}
     func add(_ key: Int) { data[key] = true }
     func remove(_ key: Int) { data[key] = nil }
     func contains(_ key: Int) -> Bool { data[key] ?? false }
}
// Bitwise Solution: --
class MyHashSet2 {
    private var bits =  [Int](repeating: 0, count: 1000001) // 15_626 = 1_000_000 / 64 + 1
    func add(_ key: Int) { bits[key>>6] |= 1<<(key&63) }
    func remove(_ key: Int) { bits[key>>6] &= ~(1<<(key&63)) }
    func contains(_ key: Int) -> Bool { bits[key>>6] & 1<<(key&63) != 0 }
}

Leave a Comment

Your email address will not be published. Required fields are marked *