Hash Tables Dictionaries and Sets

 

When coaching developers for technical interviews, I often discuss Hash Tables. Because of their design, Hash Tables are a great solution when tackling whiteboarding problems and real-world applications. How to code a Hash Table is covered in Swift Algorithms & Data Structures. However, what isn’t mentioned are how Hash Tables work alongside other collections such as Dictionaries, Sets. This essay explores these additional types with these comparisons in mind.

 

Tables vs Dictionaries

Even folks starting out in Swift will no doubt be familiar with the classic Dictionary type. Universal to most C-based languages, Dictionaries allow you to group key-value pairs. To create a new Dictionary, one just supplies a value and a key:

var list = Dictionary<String, String>()

//add dictionary values - constant time O(1)
list["WB"] = "Wayne Bishop"
list["FB"] = "Frank Hobbs"
list["LP"] = "Larry Page"
list["AE"] = "Albert Einstein"

//retrieve keys
for s in list.keys {
    print(s)
}

//retrieve values
for v in list.values {
    print(v)
}

//retrieve value with key - constant time O(1)
let item = list["WB"] //retrieves "Wayne Bishop"

Dictionaries are useful types that handle many scenarios. Since both keys and values get supplied at the call site, one can write routines to retrieve individual keys, values or a mixture thereof. If you’ve written an app that supports networking operations, JSON or XML parsing, you’ll note many third-party libraries utilize Dictionaries. 

 

Hash Tables are a close relative to Dictionaries. Hash Tables also group key-value pairs, but their keys are generated programmatically with an additional function called a hash algorithm.  Hash Tables are often the ideal structure for managing large datasets. The reason? They also allow one to manipulate data in constant time O(1) without controlling a key: 

Posted on December 11, 2017 .