DSA - Hashmap - Resize

Introduction Previously, we discussed a custom hashmap implementation. That implementation has a lot of collisions because we are using a fixed-size array. If we want to reduce the chances of collisions, we can increase the number of slots in the hashmap, or in other words, resize our hashmap. Resizing cannot guarantee that collisions will be entirely eliminated, but it will help reduce the likelihood of one happening. Code Example private func loadFactor() -> Double?...

October 9, 2024 · 3 min · Dmytro Chumakov

DSA - HashMap - Custom Implementation

Introduction Let’s take a closer look at a HashMap implementation by building it without using the built-in dictionary in Swift. The HashMap will use a fixed-size array underneath the hash function that will transform the key into an index. In this example, the hash function is based on taking the modulo of the sum of all key.unicodeScalars integer values with the size of the array. Code Example final class HashMap<Key: StringProtocol, Value> { private var hashMap: [(key: Key, value: Value)?...

October 7, 2024 · 2 min · Dmytro Chumakov

DSA - Hashmap

What is Hashmap (aka Hash Table)? A hashmap is a data structure that implements an associative array, also called a dictionary. An associative array maps keys to values. A hash table uses a hash function to compute an index, also called a hash code, into an array of buckets or slots, from which the desired value can be found. During a lookup, the key is hashed, and the resulting hash indicates where the corresponding value is stored....

October 4, 2024 · 1 min · Dmytro Chumakov

DSA - Red-Black Tree

What is a Red-Black Tree? A Red-Black tree is a self-balancing binary search tree data structure. When the tree is modified, the new tree is rearranged and “repainted” to restore the coloring properties that constrain how unbalanced the tree can become in the worst case. source Properties A Red-Black tree has all binary search tree properties, with some additional properties: Every node is either red or black. All nil nodes are considered black....

September 30, 2024 · 1 min · Dmytro Chumakov

DSA - Binary Search Tree - Inorder

What is the BST inorder algorithm? The inorder algorithm returns values in ascending order (sorted from smallest to the largest value). Code example final class BSTNode<Value: Comparable> { var val: Value? var left: BSTNode? var right: BSTNode? init(val: Value? = nil) { self.val = val } func inorder(_ visited: inout [Value]) -> [Value] { if self.left != nil { self.left!.inorder(&visited) } if self.val != nil { visited.append(self.val!) } if self.right !...

September 28, 2024 · 1 min · Dmytro Chumakov