HashMap
Implement a complete generic hash map with separate chaining: configurable initial size and load factor, get, put, remove, resizing, iteration over keys, and a randomized test against Dictionary.
- Lessons
- Hash tables · Hash functions
This homework goes with Lessons 48 and 49, like CS61B’s HashMap homework. You will
build a map from scratch, one step at a time, and test it against Swift’s own
Dictionary. Put everything in hw17.swift.
Q1: The skeleton
Write HashMap<Key: Hashable, Value> as a structure storing an array of buckets, each
an array of key–value pairs. It takes an initial number of buckets (default 16) and a
maximum load factor (default 0.75) in its initializer. Write count, get(_:), and
put(_:_:), without resizing for now.
Show solution
struct HashMap<Key: Hashable, Value> {
private var buckets: [[(key: Key, value: Value)]]
private let maxLoad: Double
private(set) var count = 0
init(initialSize: Int = 16, maxLoad: Double = 0.75) {
precondition(initialSize > 0 && maxLoad > 0)
buckets = Array(repeating: [], count: initialSize)
self.maxLoad = maxLoad
}
private func index(for key: Key) -> Int {
let h = key.hashValue % buckets.count
return h < 0 ? h + buckets.count : h
}
func get(_ key: Key) -> Value? {
buckets[index(for: key)].first { $0.key == key }?.value
}
mutating func put(_ key: Key, _ value: Value) {
let b = index(for: key)
if let i = buckets[b].firstIndex(where: { $0.key == key }) {
buckets[b][i].value = value
} else {
buckets[b].append((key, value))
count += 1
}
}
}
var map = HashMap<String, Int>(initialSize: 4)
map.put("a", 1)
map.put("b", 2)
map.put("a", 3)
assert(map.count == 2 && map.get("a") == 3 && map.get("z") == nil)Q2: Resizing
Add resizing to put: when adding a new key would make the load factor exceed
maxLoad, double the number of buckets and rehash every pair. Expose bucketCount and
check that it grows as expected.
Show solution
struct HashMap<Key: Hashable, Value> {
private var buckets: [[(key: Key, value: Value)]]
private let maxLoad: Double
private(set) var count = 0
init(initialSize: Int = 16, maxLoad: Double = 0.75) {
buckets = Array(repeating: [], count: initialSize)
self.maxLoad = maxLoad
}
var bucketCount: Int { buckets.count }
private func index(for key: Key, in size: Int) -> Int {
let h = key.hashValue % size
return h < 0 ? h + size : h
}
func get(_ key: Key) -> Value? {
buckets[index(for: key, in: buckets.count)].first { $0.key == key }?.value
}
mutating func put(_ key: Key, _ value: Value) {
let b = index(for: key, in: buckets.count)
if let i = buckets[b].firstIndex(where: { $0.key == key }) {
buckets[b][i].value = value
return
}
if Double(count + 1) / Double(buckets.count) > maxLoad {
resize(to: buckets.count * 2)
}
buckets[index(for: key, in: buckets.count)].append((key, value))
count += 1
}
private mutating func resize(to size: Int) {
var fresh: [[(key: Key, value: Value)]] = Array(repeating: [], count: size)
for pair in buckets.joined() {
fresh[index(for: pair.key, in: size)].append(pair)
}
buckets = fresh
}
}
var map = HashMap<Int, Int>(initialSize: 4, maxLoad: 1)
for n in 1...4 { map.put(n, n) }
assert(map.bucketCount == 4)
map.put(5, 5)
assert(map.bucketCount == 8)
for n in 6...100 { map.put(n, n) }
assert(map.bucketCount == 128 && (1...100).allSatisfy { map.get($0) == $0 })The bucket index must be recomputed after a resize: the same key belongs in a different bucket once the bucket count changes.
Q3: Removing and iterating
Add remove(_:), which returns the removed value, removeAll(), and conformance to
Sequence, iterating over (key, value) pairs in bucket order. Then add keys, a sorted
array of keys when Key is Comparable.
Show solution
struct HashMap<Key: Hashable, Value> {
fileprivate var buckets: [[(key: Key, value: Value)]]
private let maxLoad: Double
private(set) var count = 0
init(initialSize: Int = 16, maxLoad: Double = 0.75) {
buckets = Array(repeating: [], count: initialSize)
self.maxLoad = maxLoad
}
private func index(for key: Key, in size: Int) -> Int {
let h = key.hashValue % size
return h < 0 ? h + size : h
}
func get(_ key: Key) -> Value? {
buckets[index(for: key, in: buckets.count)].first { $0.key == key }?.value
}
mutating func put(_ key: Key, _ value: Value) {
let b = index(for: key, in: buckets.count)
if let i = buckets[b].firstIndex(where: { $0.key == key }) {
buckets[b][i].value = value
return
}
if Double(count + 1) / Double(buckets.count) > maxLoad {
let size = buckets.count * 2
var fresh: [[(key: Key, value: Value)]] = Array(repeating: [], count: size)
for pair in buckets.joined() { fresh[index(for: pair.key, in: size)].append(pair) }
buckets = fresh
}
buckets[index(for: key, in: buckets.count)].append((key, value))
count += 1
}
@discardableResult
mutating func remove(_ key: Key) -> Value? {
let b = index(for: key, in: buckets.count)
guard let i = buckets[b].firstIndex(where: { $0.key == key }) else { return nil }
count -= 1
return buckets[b].remove(at: i).value
}
mutating func removeAll() {
buckets = Array(repeating: [], count: buckets.count)
count = 0
}
}
extension HashMap: Sequence {
func makeIterator() -> FlattenSequence<[[(key: Key, value: Value)]]>.Iterator {
buckets.joined().makeIterator()
}
}
extension HashMap where Key: Comparable {
var keys: [Key] { map(\.key).sorted() }
}
var map = HashMap<String, Int>()
for (i, word) in ["pear", "fig", "kiwi", "apple"].enumerated() { map.put(word, i) }
assert(map.remove("fig") == 1 && map.remove("fig") == nil)
assert(map.keys == ["apple", "kiwi", "pear"] && map.count == 3)
assert(map.reduce(0) { $0 + $1.value } == 0 + 2 + 3)
map.removeAll()
assert(map.count == 0 && map.get("pear") == nil)Iteration reuses the standard library: joined() flattens the buckets lazily, and its
iterator becomes the map’s. The order is the bucket order, which depends on the hash
seed and changes between runs, so keys sorts.
Q4: The randomized test
Test the map against Dictionary with 50,000 random put, get, and remove
operations on a small key range, checking the count after each, and the contents at the
end.
Show solution
struct HashMap<Key: Hashable, Value> {
private var buckets: [[(key: Key, value: Value)]] = Array(repeating: [], count: 16)
private(set) var count = 0
private func index(for key: Key, in size: Int) -> Int {
let h = key.hashValue % size
return h < 0 ? h + size : h
}
func get(_ key: Key) -> Value? {
buckets[index(for: key, in: buckets.count)].first { $0.key == key }?.value
}
mutating func put(_ key: Key, _ value: Value) {
let b = index(for: key, in: buckets.count)
if let i = buckets[b].firstIndex(where: { $0.key == key }) { buckets[b][i].value = value; return }
if Double(count + 1) / Double(buckets.count) > 0.75 {
let size = buckets.count * 2
var fresh: [[(key: Key, value: Value)]] = Array(repeating: [], count: size)
for pair in buckets.joined() { fresh[index(for: pair.key, in: size)].append(pair) }
buckets = fresh
}
buckets[index(for: key, in: buckets.count)].append((key, value))
count += 1
}
@discardableResult
mutating func remove(_ key: Key) -> Value? {
let b = index(for: key, in: buckets.count)
guard let i = buckets[b].firstIndex(where: { $0.key == key }) else { return nil }
count -= 1
return buckets[b].remove(at: i).value
}
var pairs: [(key: Key, value: Value)] { Array(buckets.joined()) }
}
var map = HashMap<Int, Int>()
var reference: [Int: Int] = [:]
var generator = SystemRandomNumberGenerator()
for step in 0..<50_000 {
let key = Int.random(in: 0..<1_000, using: &generator)
switch Int.random(in: 0..<3, using: &generator) {
case 0:
map.put(key, step)
reference[key] = step
case 1:
assert(map.get(key) == reference[key])
default:
assert(map.remove(key) == reference.removeValue(forKey: key))
}
assert(map.count == reference.count)
}
assert(Dictionary(uniqueKeysWithValues: map.pairs.map { ($0.key, $0.value) }) == reference)A key range of 1,000 with 50,000 operations makes replacements and removals of present
keys frequent. The final comparison turns the map into a Dictionary and compares whole
contents, which catches lost or duplicated pairs that individual lookups might miss.
Q5 (optional): Pluggable buckets
CS61B’s version lets subclasses choose the bucket type: arrays, linked lists, or even
trees. Make the bucket a generic parameter conforming to a small protocol, and provide
two implementations: an array bucket and a sorted-array bucket that uses binary search
for Comparable keys.
Show solution
protocol Bucket<Key, Value> {
associatedtype Key: Hashable
associatedtype Value
init()
func get(_ key: Key) -> Value?
mutating func put(_ key: Key, _ value: Value) -> Bool // true if the key was new
var pairs: [(key: Key, value: Value)] { get }
}
struct ArrayBucket<Key: Hashable, Value>: Bucket {
private(set) var pairs: [(key: Key, value: Value)] = []
func get(_ key: Key) -> Value? { pairs.first { $0.key == key }?.value }
mutating func put(_ key: Key, _ value: Value) -> Bool {
if let i = pairs.firstIndex(where: { $0.key == key }) { pairs[i].value = value; return false }
pairs.append((key, value)); return true
}
}
struct SortedBucket<Key: Hashable & Comparable, Value>: Bucket {
private(set) var pairs: [(key: Key, value: Value)] = []
private func position(_ key: Key) -> Int {
var (low, high) = (0, pairs.count)
while low < high {
let mid = (low + high) / 2
if pairs[mid].key < key { low = mid + 1 } else { high = mid }
}
return low
}
func get(_ key: Key) -> Value? {
let i = position(key)
return i < pairs.count && pairs[i].key == key ? pairs[i].value : nil
}
mutating func put(_ key: Key, _ value: Value) -> Bool {
let i = position(key)
if i < pairs.count && pairs[i].key == key { pairs[i].value = value; return false }
pairs.insert((key, value), at: i); return true
}
}
struct Map<B: Bucket> {
private var buckets = Array(repeating: B(), count: 8)
private(set) var count = 0
private func index(_ key: B.Key) -> Int { let h = key.hashValue % buckets.count; return h < 0 ? h + buckets.count : h }
func get(_ key: B.Key) -> B.Value? { buckets[index(key)].get(key) }
mutating func put(_ key: B.Key, _ value: B.Value) {
if buckets[index(key)].put(key, value) {
count += 1
if count > buckets.count {
let pairs = buckets.flatMap(\.pairs)
buckets = Array(repeating: B(), count: buckets.count * 2)
for p in pairs { _ = buckets[index(p.key)].put(p.key, p.value) }
}
}
}
}
var a = Map<ArrayBucket<Int, String>>()
var s = Map<SortedBucket<Int, String>>()
for n in 0..<500 { a.put(n, "\(n)"); s.put(n, "\(n)") }
assert(a.count == 500 && s.count == 500 && a.get(321) == "321" && s.get(321) == "321" && s.get(999) == nil)The map is written once against the protocol, and the bucket type is chosen when the map is created: Lesson 31’s interfaces used for performance tuning. With a good hash, buckets hold one or two pairs and the choice hardly matters; with a bad hash, sorted buckets turn a linear scan into a binary search.