Linked list and hashmap
When we are developing software, we have to store data in memory. However, many types of data structures, such as arrays, maps, sets, lists, trees, graphs, etc., and choosing the right one for the task can be tricky. This series of posts will help you know the trade-offs so that you can use the right tool for the job! Show
This section will focus on linear data structures: Arrays, Lists, Sets, Stacks, and Queues. You can find all these implementations and more in the Github repo: https://github.com/amejiarosario/dsa.js This post is part of a tutorial series: Learning Data Structures and Algorithms (DSA) for Beginners
Data Structures Big-O CheatsheetThe following table is a summary of everything that we are going to cover.
Click on the name to go to the section or click on the runtime to go to the implementation * = Amortized runtime
Note: Binary search trees and trees, in general, will be cover in the next post. Also, graph data structures. Primitive Data TypesPrimitive data types are the most basic elements, where all the other data structures are built upon. Some primitives are:
JavaScript specific primitives:
Note: Objects are not primitive since they are composed of zero or more primitives and other objects. ArrayArrays are collections of zero or more elements. Arrays are one of the most used data structures because of their simplicity and fast way of retrieving information. You can think of an array as a drawer where you can store things in the bins. Array is like a drawer that stores things on bins When you want to search for something, you can go directly to the bin number. Thats a constant time operation (O(1)). However, if you forgot what cabinet had, you will have to open one by one (O(n)) to verify its content until you find what you are looking for. That same happens with an array. Depending on the programming language, arrays have some differences. For some dynamic languages like JavaScript and Ruby, an array can contain different data types: numbers, strings, words, objects, and even functions. In typed languages like Java/C/C++, you have to predefine the Array size and the data type. In JavaScript, it would automatically increase the size of the Array when needed. Arrays built-in operationsDepending on the programming language, the implementation would be slightly different. For instance, in JavaScript, we can accomplish append to end with push and append to the beginning with unshift. But also, we have pop and shift to remove from an array. Lets describe some everyday operations that we are going to use through this post. Common JS Array built-in functions
Insert element on an arrayThere are multiple ways to insert elements into an array. You can append new data to the end or add it to the beginning of the collection. Lets start with append to tail:
Based on the language specification, push just set the new value at the end of the Array. Thus,
Lets now try appending to head:
What do you think is the runtime of the insertToHead function? It looks the same as the previous one, except that we are using unshift instead of push. But theres a catch! unshift algorithm makes room for the new element by moving all existing ones to the next position in the Array. So, it will iterate through all the elements.
Access an element in an arrayIf you know the index for the element that you are looking for, then you can access the element directly like this:
As you can see in the code above, accessing an element on an array has a constant time:
Note: You can also change any value at a given index in constant time. Search an element in an arraySuppose you dont know the index of the data that you want from an array. You have to iterate through each element on the Array until we find what we are looking for.
Given the for-loop, we have:
Deleting elements from an arrayWhat do you think is the running time of deleting an element from an array? Well, lets think about the different cases:
Talk is cheap. Lets do the code!
So we are using our search function to find the elements index O(n). Then we use the JS built-in splice function, which has a running time of O(n). Whats the total O(2n)? Remember, we constants dont matter as much. We take the worst-case scenario:
Array operations time complexityWe can sum up the arrays time complexity as follows: Array Time Complexities
HashMapsMaps, dictionaries, and associative arrays all describe the same abstract data type. But hash map implementations are distinct from treemap implementations in that one uses a hash table and one uses a binary search tree.
Going back to the drawer analogy, bins have a label rather than a number. HashMap is like a drawer that stores things on bins and labels them In this example, if you are looking for the book, you dont have to open bin 1, 2, and 3. You go directly to the container labeled as books. Thats a huge gain! Search time goes from O(n) to O(1). In arrays, the data is referenced using a numeric index (relatively to the position). However, HashMaps uses labels that could be a string, number, Object, or anything. Internally, the HashMap uses an Array, and it maps the labels to array indexes using a hash function. There are at least two ways to implement hashmap:
We will cover Trees & Binary Search Trees, so dont worry about it for now. The most common implementation of Maps is using an array and hash function. So, thats the one we are going to focus on. HashMap implemented with an array As you can see in the image, each key gets translated into a hash code. Since the array size is limited (e.g., 10), we have to loop through the available buckets using the modulus function. In the buckets, we store the key/value pair, and if theres more than one, we use a collection to hold them. Now, What do you think about covering each of the HashMap components in detail? Lets start with the hash function. HashMap vs. ArrayWhy go through the trouble of converting the key into an index and not using an array directly, you might ask. The main difference is that Arrays index doesnt have any relationship with the data. You have to know where your data is. Lets say you want to count how many times words are used in a text. How would you implement that?
What is the runtime of approach #1 using two arrays? If we say, the number of words in the text is n. Then we have to search if the word in the array A and then increment the value on array B matching that index. For every word on n, we have to test if its already on array A. This double loop leave use with a runtime of O(n2). What is the runtime of approach #2 using a HashMap? We iterate through each word on the text once and increment the value if there is something there or set it to 1 if that word is seen for the first time. The runtime would be O(n), which is much more performant than approach #1. Differences between HashMap and Array
Hash FunctionThe first step to implement a HashMap is to have a hash function. This function will map every key to its value.
Ideal hashing algorithms allow constant time access/lookup. However, its hard to achieve a perfect hashing function in practice. You might have the case where two different keys yields on the same index, causing a collision. Collisions in HashMaps are unavoidable when using an array-like underlying data structure. At some point, data that cant fit in a HashMap will reuse data slots. One way to deal with collisions is to store multiple values in the same bucket using a linked list or another array (more on this later). When we try to access the keys value and found various values, we iterate over the values O(n). However, in most implementations, the hash adjusts the size dynamically to avoid too many collisions. We can say that the amortized lookup time is O(1). We are going to explain what we mean by amortized runtime later in this post with an example. Naïve HashMap implementationA simple (and bad) hash function would be this one: Naive HashMap Implementationfull code
We are using buckets rather than drawer/bins, but you get the idea :) We have an initial capacity of 2 (two buckets). But, we want to store any number of elements on them. We use modulus % to loop through the number of available buckets. Take a look at our hash function in line 18. We are going to talk about it in a bit. First, lets use our new HashMap!
This Map allows us to set a key and a value and then get the value using a key. The key part is the hash function. Lets see multiple implementations to see how it affects the Maps performance. Can you tell whats wrong with NaiveHashMap before expanding the answer below? What is wrong with `NaiveHashMap` is that...
This hash implementation will cause a lot of collisions.
Did you guess any? ️ Improving Hash Function
For that, we need:
Lets give it another shot at our hash function. Instead of using the strings length, lets sum each character ascii code.
Lets try again:
This one is better! Because words with the same length have different codes. Howeeeeeeeeever, theres still an issue! Because rat and art are both 327, collision! We can fix that by offsetting the sum with the position:
Now lets try again, this time with hex numbers so we can see the offset.
What about different types?
Houston, we still have a problem!! Different value types shouldnt return the same hash code! How can we solve that? One way is taking into account the key type into the hash function.
Lets test that again:
Yay!!! We have a much better hash function! We also can change the initial capacity of the Array to minimize collisions. Lets put all of that together in the next section. Decent HashMap ImplementationUsing our optimized hash function, we can now do much better. We could still have collisions, so lets implement something to handle them. Lets make the following improvements to our HashMap implementation:
Lets use it and see how it perform:
This DecentHashMap gets the job done, but there are still some issues. We are using a decent hash function that doesnt produce duplicate values, and thats great. However, we have two values in bucket#0 and two more in bucket#1. How is that possible? Since we are using a limited bucket size of 2, we use modulus % to loop through the number of available buckets. So, even if the hash code is different, all values will fit on the Array size: bucket#0 or bucket#1.
So naturally, we have increased the initial capacity, but by how much? Lets see how the initial size affects the hash map performance. If we have an initial capacity of 1. All the values will go into one bucket (bucket#0), and it wont be any better than searching a deal in a simple array O(n). Lets say that we start with an initial capacity set to 10:
Another way to see this As you can see, we reduced the number of collisions (from 2 to 1) by increasing the hash maps initial capacity. Lets try with a bigger capacity :
Yay! no collision! Having a bigger bucket size is excellent to avoid collisions, but it consumes too much memory, and probably most of the buckets will be unused. Wouldnt it be great if we can have a HashMap that automatically increases its size as needed? Well, thats called ** rehash**, and we are going to do it next! Optimal HashMap ImplementationIf we have a big enough bucket, we wont have collisions; thus, the search time would be O(1). However, how do we know how big a hash map capacity should big? 100? 1,000? A million? Having allocated massive amounts of memory is impractical. So, we can automatically have the hash map resize itself based on a load factor. This operation is called ** rehash**. The load factor is the measurement of how full is a hash map. We can get the load factor by dividing the number of items by the bucket size. This will be our latest and greatest hash map implementation: **Optimized Hash Map Implementation _(click here to show the code)_**Optimal HashMap Implementationdocumented code
Pay special attention to lines 96 to 114. Thats where the rehash magic happens. We create a new HashMap with doubled capacity. So, testing our new implementation from above ^
Take notice that after we add the 12th item, the load factor gets beyond 0.75, so a rehash is triggered and doubles the capacity (from 16 to 32). Also, you can see how the number of collisions improves from 2 to 0! This implementation is good enough to help us figure out the runtime of standard operations like insert/search/delete/edit. To sum up, the performance of a HashMap will be given by:
We nailed both . We have a decent hash function that produces different outputs for different data. Two distinct data will never return the same code. Also, we have a rehash function that automatically grows the capacity as needed. Thats great! Insert element on a HashMap runtimeInserting an element on a HashMap requires two things: a key and a value. We could use our DecentHashMap data structure that we develop or use the built-in as follows:
In modern JavaScript, you can use Maps.
Note: We will use the Map rather than the regular Object, since the Maps key could be anything while on Objects key can only be string or number. Also, Maps keeps the order of insertion. Behind the scenes, the Map.set just insert elements into an array (take a look at DecentHashMap.set). So, similar to Array.push we have that:
Our implementation with rehash functionality will keep collisions to the minimum. The rehash operation takes O(n), but it doesnt happen all the time, only when it is needed. Search/Access an element on a HashMap runtimeThis is the HashMap.get function that we use to get the value associated with a key. Lets evaluate the implementation from DecentHashMap.get):
If theres no collision, then values will only have one value, and the access time would be O(1). But, we know there will be collisions. If the initial capacity is too small and the hash function is terrible like NaiveHashMap.hash, then most of the elements will end up in a few buckets O(n).
Advanced Note: Another idea to reduce the time to get elements from O(n) to O(log n) is to use a binary search tree instead of an array. Actually, Javas HashMap implementation switches from an array to a tree when a bucket has more than 8 elements. Edit/Delete element on a HashMap runtimeEditing (HashMap.set) and deleting (HashMap.delete) key/value pairs have an amortized runtime of O(1). In the case of many collisions, we could face an O(n) as a worst-case. However, with our rehash operation, we can mitigate that risk.
HashMap operations time complexityWe can sum up the arrays time complexity as follows: HashMap Time Complexities
SetsSets are very similar to arrays. The difference is that they dont allow duplicates. How can we implement a Set (Array without duplicates)? We could use an array and check if an element is there before inserting a new one. But the running time of checking if a value is already there is O(n). Can we do better than that? We develop the Map with an amortized run time of O(1)! Set ImplementationWe could use the JavaScript built-in Set. However, if we implement it by ourselves, its more logical to deduct the runtimes. We are going to use the optimized HashMap with rehash functionality.
We used HashMap.set to add the set elements without duplicates. We use the key as the value, and since the hash maps keys are unique, we are all set. Checking if an element is already there can be done using the hashMap.has, which has an amortized runtime of O(1). Most operations would be an amortized constant time except for getting the entries, O(n). Note: The JS built-in Set.has has a runtime of O(n) since it uses a regular list of elements and checks each one at a time. You can see the Set.has algorithm here Here some examples how to use it:
You should be able to use MySet and the built-in Set interchangeably for these examples. Set Operations runtimeFrom our Set implementation using a HashMap, we can sum up the time complexity as follows (very similar to the HashMap): Set Time Complexities
Linked ListsA linked list is a data structure where every element is connected to the next one. The linked list is the first data structure that we are going to implement without using an array. Instead, we will use a node that holds a value and points to the next element. node.js
When we have a chain of nodes where each one points to the next one, we a Singly Linked list. Singly Linked ListsFor a singly linked list, we only have to worry about every element referencing the next one. We start by constructing the root or head element. linked-list.js
There are four basic operations that we can do in every Linked List:
Adding/Removing an element at the end of a linked list There are two primary cases:
Whats the runtime of this code? If it is the first element, then adding to the root is O(1). However, finding the last item is O(n). Now, removing an element from the end of the list has a similar code. We have to find the current before last and make its next reference null. LinkedList.prototype.removeLast
The runtime again is O(n) because we have to iterate until the second-last element and remove the reference to the last (line 10). Adding/Removing an element from the beginning of a linked list Adding an element to the head of the list is like this: LinkedList.addFirst
Adding and removing elements from the beginning is a constant time because we hold a reference to the first element: LinkedList.removeFirst
As expected, the runtime for removing/adding to the first element from a linked List is always constant O(1) Removing an element anywhere from a linked list Removing an element anywhere in the list leverage the removeLast and removeFirst. However, if the removal is in the middle, then we assign the previous node to the next one. That removes any reference from the current node, this is removed from the list: LinkedList.remove
Note that index is a zero-based index: 0 will be the first element, 1 second, and so on.
Searching for an element in a linked list Searching an element on the linked list is very somewhat similar to remove: LinkedList.contains
This function finds the first element with the given value.
Singly Linked Lists time complexitySingly Linked List time complexity per function is as follows.
Notice that every time we add/remove from the last position, the operation takes O(n).
We are going to add the last reference in the next section! Doubly Linked ListsWhen we have a chain of nodes where each one points to the next one, we have a Singly Linked list. When we have a linked list where each node leads to the next and the previous element, we have a Doubly Linked List Doubly linked list nodes have double references (next and previous). We are also going to keep track of the list first and the last element. Doubly Linked Listfull code
Adding and Removing from the start of a list Adding and removing from the start of the list is simple since we have this.first reference: LinkedList.prototype.addFirstfull code
Notice that we have to be very careful and update the previous and last reference. LinkedList.prototype.removeFirstfull code
Whats the runtime?
Adding and removing from the end of a list Adding and removing from the end of the list is a little tricky. If you checked in the Singly Linked List, both operations took O(n) since we had to loop through the list to find the last element. Now, we have the last reference: LinkedList.prototype.addLastfull code
Again, we have to be careful about updating the references and handling exceptional cases such as only one element. LinkedList.prototype.removeLastfull code
Using a doubly-linked list, we no longer have to iterate through the whole list to get the 2nd last element. We can use directly this.last.previous and is O(1). Did you remember that for the Queue, we had to use two arrays? We can now change that implementation and use a doubly-linked list instead. The runtime will be O(1) for insert at the start and deleting at the end. Adding an element anywhere from a linked list Adding an element on anywhere on the list leverages our addFirst and addLast functions as you can see below: LinkedList.addFullCode
If we have an insertion in the middle of the Array, then we have to update the next and previous reference of the surrounding elements.
Doubly Linked Lists time complexityDoubly Linked List time complexity per function is as follows:
Doubly linked lists are a significant improvement compared to the singly linked list! We improved from O(n) to O(1) by:
Removing first/last can be done in constant time; however, eliminating in the middle of the Array is still O(n). StacksStacks is a data structure where the last entered data is the first to come out. Also know as Last-in, First-out (LIFO). Lets implement a stack from scratch!
As you can see, it is easy since we are using the built-in Array.push and Array.pop. Both have a runtime of O(1). Lets see some examples of its usage:
The first element in (a) is the last to get out. We can also implement Stack using a linked list instead of an array. The runtime will be the same. Thats all! QueuesQueues are a data structure where the first data to get in is also the first to go out. A.k.a First-in, First-out (FIFO). Its like a line of people at the movies, the first to come in is the first to come out. We could implement a Queue using an array, very similar to how we implemented the Stack. Queue implemented with Array(s)A naive implementation would be this one using Array.push and Array.shift:
Whats the time complexity of Queue.add and Queue.remove?
Think of how you can implement a Queue only using Array.push and Array.pop.
Now we are using two arrays rather than one.
When we remove something for the first time, the output array is empty. So, we insert the content of input backward like ['b', 'a']. Then we pop elements from the output array. As you can see, using this trick, we get the output in the same order of insertion (FIFO). Whats the runtime? If the output already has some elements, then the remove operation is constant O(1). When the output arrays need to get refilled, it takes O(n) to do so. After the refilled, every operation would be constant again. The amortized time is O(1). We can achieve a Queue with a pure constant if we use LinkedList. Lets see what it is in the next section! Queue implemented with a Doubly Linked ListWe can achieve the best performance for a queue using a linked list rather than an array.
Using a doubly-linked list with the last element reference, we achieve an add of O(1). Thats the importance of using the right tool for the right job. SummaryWe explored most of the linear data structures. We saw that depending on how we implement the data structures. There are different runtimes. Heres a summary of everything that we explored. You can click on each runtime, and it will take you to the implementation. Time complexity Click on the name to go to the section or click on the runtime to go to the implementation * = Amortized runtime
Note: Binary search trees and trees, in general, will be cover in the next post. Also, graph data structures. |