A Hash Set is an unordered collection of unique elements, where elements are stored in a table using a hash function. In my implementation, elements are stored in an Array of Linked Lists.

Quick Facts

  • An unordered collection of unique elements.
  • Elements in set must be hashable.
  • Swift’s Set implementation in Foundation is a Hash Set.

Use Cases

  • Test efficiency for membership.
  • When not concerned about order of elements.
  • When need to ensure elements in collection only appear once.

Structure

var isEmpty: Bool

Returns true if the set is empty or false if it contains elements.

var count: Int

Returns the number of elements in the set.

func insert(_ element: Element) -> Bool

Inserts the element into the set the set does not already contain it. Returns true if the element was inserted and false if it was not.

func remove(_ element: Element) -> Element?

Removes an element from the set. Returns the element if it is in the set.

func removeAll()

Removes all elements from the set.

func contains(_ element: Element) -> Element?

Tests for membership. The element is returned if the set contains it.

func union(_ hashSet: HashSet) -> HashSet

Returns a new set with the elements of both this set and the given set.

func intersection(_ hashSet: HashSet) -> HashSet

Returns a new set with the elements that are common to both this set and the given set.

func difference(_ hashSet: HashSet) -> HashSet

Removes the elements of the given set from this set.


References

  1. https://developer.apple.com/documentation/swift/set
  2. https://github.com/raywenderlich/swift-algorithm-club/tree/master/Hash%20Set
  3. https://developer.apple.com/documentation/swift/hashable

Leave a Reply