<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Hash tables - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Hash tables - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 11 Jun 2026 05:19:25 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/hash-tables/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What is a Hash Map? Time Complexity and Two Sum Example ]]>
                </title>
                <description>
                    <![CDATA[ A hash table or hash map, is a data structure that helps with mapping keys to values for highly efficient operations like the lookup, insertion and deletion operations. In this tutorial, you'll learn the following: Constant and linear time complexit... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-hash-map/</link>
                <guid isPermaLink="false">66ba2fd8de9370f66eeb0aa1</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data structures ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Hash tables ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Mapping ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sule-Balogun Olanrewaju ]]>
                </dc:creator>
                <pubDate>Thu, 25 Jan 2024 17:02:13 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/joan-gamell-ZS67i1HLllo-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A hash table or hash map, is a data structure that helps with mapping keys to values for highly efficient operations like the lookup, insertion and deletion operations.</p>
<p>In this tutorial, you'll learn the following:</p>
<ul>
<li>Constant and linear time complexity.</li>
<li>Why use a hash map?</li>
<li>Things to consider when writing hash functions.</li>
<li>How to solve the Two Sum problem in PHP and JavaScript.</li>
</ul>
<h2 id="heading-what-is-constant-time-complexity-o1">What is Constant Time Complexity - O(1)?</h2>
<p>O(1) indicates that the running time of an algorithm is constant, regardless of the input size. </p>
<p>This implies that the algorithm's performance isn't dependent on the size of the input. An example is accessing an index of an array.</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">constantTimeAlgorithm</span>(<span class="hljs-params">$arr</span>) 
</span>{

    <span class="hljs-keyword">echo</span> $arr[<span class="hljs-number">0</span>] . PHP_EOL;
}
</code></pre>
<p>Here is a non-code example to illustrate the concept of constant time complexity:</p>
<p>Imagine sending a file through an airline to your friend, and the airline has a policy where they charge based on the weight of the package.</p>
<p>Now, whether your file weighs 2 grams or 20 kilograms, the airline's processing time remains constant. This means that the time it takes for the airline to handle your package doesn't depend on the weight of the file – it's always the same. </p>
<p>In other words, the processing time is constant irrespective of the size of the file.</p>
<h2 id="heading-what-is-linear-time-complexity-on">What is Linear Time Complexity - O(n)?</h2>
<p>O(n) indicates that the running time of an algorithm grows linearly with the size of the input. </p>
<p>The performance of the algorithm is directly proportional to the input size. An example is traversing a <code>for</code> loop and printing elements.</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">linearTimeAlgorithm</span>(<span class="hljs-params">$arr</span>) 
</span>{
    <span class="hljs-keyword">foreach</span> ($arr <span class="hljs-keyword">as</span> $element) {
        <span class="hljs-keyword">echo</span> $element . PHP_EOL;
    }
}
</code></pre>
<p>Here's a non-code example to illustrate the concept of linear time complexity:</p>
<p>Consider using an electronic transfer service to send a file to your friend. In this scenario, the time it takes to transfer the file increases linearly with the size of the file. </p>
<p>For instance, if it takes 1 minutes to transfer a 100 MB file, it would take approximately 100 minutes to transfer a 10 GB file using the same service. </p>
<p>This linear relationship between the size of the file and the time it takes to transfer it reflects linear time complexity. The time taken to transfer the file increases proportionally or linearly with the size of the input or file.</p>
<h2 id="heading-why-use-a-hash-map">Why use a Hash Map?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-108.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration of how a hash map works</em></p>
<p>A hash map is a concrete implementation of the abstract data type known as an associative array. </p>
<p>In a hash map, keys are hashed to determine the index where the corresponding values will be stored, allowing for efficient retrieval and storage of key-value pairs. </p>
<p>This implementation typically provides fast access times for operations like insertion, deletion, and lookup of values based on their associated keys. </p>
<p>In languages like PHP or JavaScript, when you use an associative array, you are essentially using a hash map. Their associative arrays are implemented using hash tables behind the scenes. </p>
<p>You can use strings, integers, or other data types as keys, and the language's internal hashing mechanism efficiently maps these keys to their corresponding values. Additionally, JavaScript provides the <code>Map</code> object for more advanced hash map functionalities.</p>
<h3 id="heading-time-and-space-complexity-for-hash-map">Time and Space Complexity for Hash Map</h3>
<p>The time and space complexity for a hash map (or hash table) is not necessarily O(n) for all operations. The typical and desired time complexity for basic operations like insertion, lookup, and deletion in a well-designed hash map is O(1) on average. </p>
<p>Here's a breakdown of time and space complexity for a hash map:</p>
<h4 id="heading-time-complexity">Time Complexity:</h4>
<p>Average Case:</p>
<ul>
<li>Insertion (average): O(1)</li>
<li>Lookup (average): O(1)</li>
<li>Deletion (average): O(1)</li>
</ul>
<p>Worst Case:</p>
<ul>
<li>Insertion (worst): O(n), where n is the size of the hash map. This occurs when there are many hash collisions, leading to linear probing or other collision resolution strategies that may involve traversing the entire hash map.</li>
<li>Lookup and Deletion (worst): O(n), for the same reason as insertion.</li>
</ul>
<h4 id="heading-space-complexity">Space Complexity:</h4>
<ul>
<li>The space complexity is typically O(n). Where n is the number of key-value pairs stored in the hash map. Each key-value pair occupies constant space, and the space required grows linearly with the number of elements.</li>
</ul>
<p>In algorithm analysis, the notation O(1) and O(n) represent the upper bounds on the time complexity of an algorithm, where n is the size of the input.</p>
<h4 id="heading-operations">Operations</h4>
<ol>
<li><strong>Insertion:</strong> The key-value pair is hashed, and the resulting index is used to store the value in the corresponding slot. If a collision occurs, the collision resolution strategy is applied.</li>
<li><strong>Deletion:</strong> The key is hashed to find the index, and the item at that index is removed. Collision resolution may be necessary.</li>
<li><strong>Lookup:</strong> The key is hashed to find the index, and the value at that index is returned. Collision resolution may be applied if needed.</li>
</ol>
<h2 id="heading-things-to-consider-when-creating-hash-tables">Things to consider When Creating Hash Tables</h2>
<p>When creating hash tables, there are several important considerations to ensure efficiency, including fast computation of hash codes and effective collision resolution strategies.</p>
<h3 id="heading-fast-computation">Fast Computation</h3>
<p>Hash codes should be computed quickly to ensure efficient insertion, lookup, and deletion operations. A good hash function contributes to the speed of hash code computation.</p>
<h3 id="heading-avoid-collision">Avoid collision</h3>
<p>A collision happens when two or more keys produce the same hash code. In other words, multiple keys map to the same array index.</p>
<h2 id="heading-how-to-handle-collisions">How to Handle Collisions</h2>
<p>Hash maps use collision resolution techniques to deal with collisions. Common strategies include:</p>
<h4 id="heading-chaining">Chaining</h4>
<p>To manage several values with the same hash code, chaining involves storing a linked list or other data structure at each array index.  If a collision occurs, the new key-value pair is appended to the linked list at the relevant index.</p>
<h4 id="heading-open-addressing">Open addressing</h4>
<p>When a collision happens in a hash table, a technique called open addressing is employed to resolve it by searching for the next open space. </p>
<p>All it does is search the array for the next empty slot where the key-value combination can be placed. Methods including double hashing, quadratic probing, and linear probing are applied.</p>
<p><strong>Linear Probing:</strong> In linear probing, the algorithm moves linearly to the next index in the array in order to find the next open slot when a collision occurs.</p>
<p><strong>Quadratic Probing:</strong> In this method, an algorithm employs a quadratic function to find the next slot that becomes available.</p>
<p><strong>Double Hashing:</strong> In double hashing, the algorithm calculates the step size between probes using a secondary hash function.</p>
<p>In order to reduce the possibility of collisions, a good hash function should generate distinct hash codes for various inputs. By making sure the hash codes are evenly distributed throughout the range of potential values, collisions can be prevented.</p>
<h2 id="heading-how-to-solve-the-two-sum-problem">How to Solve the Two Sum Problem</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-117.png" alt="Image" width="600" height="400" loading="lazy">
<em>Two sum problem</em></p>
<p>The Two Sum problem involves finding all pairs of elements in an array that sum up to a specific target value. Now let's look at the problem statement.</p>
<h3 id="heading-problem-statement">Problem statement</h3>
<p>Given an array of integers <code>nums</code> and an integer <code>target</code>, return the indices of the two numbers such that they add up to the <code>target</code>.</p>
<p><em>Example 1:</em></p>
<p><strong>Input:</strong> nums = [3,2,4, 8], target = 12</p>
<p><strong>Output:</strong> [2, 3]</p>
<p><em>Example 2:</em></p>
<p><strong>Input:</strong> nums = [5,5], target = 10 </p>
<p><strong>Output:</strong> [0,1]</p>
<h3 id="heading-solution">Solution</h3>
<p>To solve the Two Sum problem, we can use a hash table. The idea is to traverse the <code>nums</code> array and, for each element, check if the complement (the difference between the target and the current element) is already in the hash table. If it is, we have found a pair of indices whose elements add up to the target.</p>
<p>Here are the steps to follow:</p>
<ol>
<li>To hold the elements and their respective indices, create an empty hash table upon initialization.</li>
<li>Go over the array of <code>nums</code>.</li>
<li>Do the complement calculation (target - current element) for each element.</li>
<li>Verify if the complement has already been added to the hash table.  If yes, return the current index and the index stored in the hash table for the complement.</li>
<li>If the complement is not in the hash table, store the current element and its index in the hash table.</li>
<li>If no such pair is found during the traversal, it implies that there is no solution.</li>
</ol>
<h5 id="heading-php-code-solution">PHP Code Solution</h5>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">twoSum</span>(<span class="hljs-params">$nums, $target</span>) </span>{
    $hashTable = [];

    <span class="hljs-keyword">foreach</span> ($nums <span class="hljs-keyword">as</span> $i =&gt; $num) {
        $complement = $target - $num;

        <span class="hljs-keyword">if</span> (array_key_exists($complement, $hashTable)) {

            <span class="hljs-comment">// Found the pair, return the indices</span>
            <span class="hljs-keyword">return</span> [$hashTable[$complement], $i];
        }

        <span class="hljs-comment">// Store the current element in the hash table</span>
        $hashTable[$num] = $i;
    }

    <span class="hljs-comment">// No solution found</span>
    <span class="hljs-keyword">return</span> [];
}

<span class="hljs-comment">// Example usage:</span>
$nums = [<span class="hljs-number">2</span>, <span class="hljs-number">7</span>, <span class="hljs-number">11</span>, <span class="hljs-number">5</span>, <span class="hljs-number">15</span>, <span class="hljs-number">30</span>];
$target = <span class="hljs-number">12</span>;
$result = twoSum($nums, $target);

<span class="hljs-keyword">echo</span> <span class="hljs-string">"Indices of the two numbers: ["</span> . implode(<span class="hljs-string">", "</span>, $result) . <span class="hljs-string">"]"</span>;
</code></pre>
<h5 id="heading-javascript-code-solution-using-map-function">JavaScript Code Solution using <code>map</code> Function</h5>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">twoSum</span>(<span class="hljs-params">nums, target</span>) </span>{
    <span class="hljs-keyword">const</span> hashTable = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [index, num] <span class="hljs-keyword">of</span> nums.entries()) {
        <span class="hljs-keyword">const</span> complement = target - num;

        <span class="hljs-comment">// Check if the complement is in the Map</span>
        <span class="hljs-keyword">if</span> (hashTable.has(complement)) {

            <span class="hljs-comment">// Found the pair, return the indices</span>
            <span class="hljs-keyword">return</span> [hashTable.get(complement), index];
        }

        <span class="hljs-comment">// Store the current number and its index in the Map</span>
        hashTable.set(num, index);
    }

    <span class="hljs-comment">// No solution found</span>
    <span class="hljs-keyword">return</span> [];
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-keyword">const</span> nums = [<span class="hljs-number">2</span>, <span class="hljs-number">7</span>, <span class="hljs-number">11</span>, <span class="hljs-number">5</span>, <span class="hljs-number">15</span>, <span class="hljs-number">30</span>];
<span class="hljs-keyword">const</span> target = <span class="hljs-number">12</span>;
<span class="hljs-keyword">const</span> result = twoSum(nums, target);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Indices of the two numbers that add up to <span class="hljs-subst">${target}</span>: [<span class="hljs-subst">${result.join(<span class="hljs-string">', '</span>)}</span>]`</span>);
</code></pre>
<p>This approach has a time complexity of O(n) because we iterate through the array once. The space complexity is also O(n) due to the storage of elements in the hash map.</p>
<h2 id="heading-resources">Resources</h2>
<ol>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Hash_table">Hash table From Wikipedia</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=RcZsTI5h0kg">Hash maps in Python</a></li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned about hash maps, things to consider when writing hash functions and a real world problem that involves solving the Two Sum problem.</p>
<p>Keep learning, and Happy Coding!</p>
<p>You can find me on <a target="_blank" href="https://www.linkedin.com/in/suleolanrewaju/">LinkedIn</a> and <a target="_blank" href="https://twitter.com/bigdevlarry">Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Hash Table – Associative Array Hashing in JS ]]>
                </title>
                <description>
                    <![CDATA[ Hash Tables are a data structure that allow you to create a list of paired values. You can then retrieve a certain value by using the key for that value, which you put into the table beforehand. A Hash Table transforms a key into an integer index usi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-hash-table-associative-array-hashing-in-js/</link>
                <guid isPermaLink="false">66bd917ddc6141cf21aaadba</guid>
                
                    <category>
                        <![CDATA[ data structures ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Hash tables ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Tue, 11 May 2021 15:24:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/05/JavaScript-Hash-Table.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hash Tables are a data structure that allow you to create a list of paired values. You can then retrieve a certain value by using the key for that value, which you put into the table beforehand.</p>
<p>A Hash Table transforms a key into an integer index using a hash function, and the index will decide where to store the key/value pair in memory:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/g983.jpg" alt="Image" width="600" height="400" loading="lazy">
_Hash table for storing phone books (from <a target="_blank" href="https://en.wikipedia.org/wiki/Hash_table">Wikipedia</a>)_</p>
<p>You'll commonly use a Hash Table because of its fast search, insertion, and delete operations:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td>Hash Table time complexity in Big O Notation</td><td></td></tr>
</thead>
<tbody>
<tr>
<td>Algorithm</td><td>Average</td><td>Worst case</td></tr>
<tr>
<td>Space</td><td>O(n)</td><td>O(n)</td></tr>
<tr>
<td>Search</td><td>O(1)</td><td>O(n)</td></tr>
<tr>
<td>Insert</td><td>O(1)</td><td>O(n)</td></tr>
<tr>
<td>Delete</td><td>O(1)</td><td>O(n)</td></tr>
</tbody>
</table>
</div><p><small>Source from <a target="_blank" href="https://en.wikipedia.org/wiki/Hash_table">Wikipedia</a></small></p>
<p>This tutorial will help you understand Hash Table implementation in JavaScript as well as how you can build your own Hash Table class. </p>
<p>First, let's look at JavaScript's <code>Object</code> and <code>Map</code> classes.</p>
<h2 id="heading-how-to-use-hash-tables-with-object-and-map-classes-in-javascript">How to Use Hash Tables with Object and Map Classes in JavaScript</h2>
<p>The most common example of a Hash Table in JavaScript is the <code>Object</code> data type, where you can pair the object's property value with a property key.</p>
<p>In the following example, the key <code>Nathan</code> is paired with the phone number value of <code>"555-0182"</code> and the key <code>Jane</code> is paired with the value <code>"315-0322"</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> obj = {
  <span class="hljs-attr">Nathan</span>: <span class="hljs-string">"555-0182"</span>,
  <span class="hljs-attr">Jane</span>: <span class="hljs-string">"315-0322"</span>
}
</code></pre>
<p>But JavaScript's <code>Object</code> type is a special kind of Hash Table implementation for two reasons:</p>
<ul>
<li>It has properties added by the <code>Object</code> class. Keys you input may conflict and overwrite default properties inherited from the class.</li>
<li>The size of the Hash Table is not tracked. You need to manually count how many properties are defined by the programmer instead of inherited from the prototype.</li>
</ul>
<p>For example, the <code>Object</code> prototype has the <code>hasOwnProperty()</code> method which allows you to check if a property is not inherited:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = {};
obj.name = <span class="hljs-string">"Nathan"</span>;

<span class="hljs-built_in">console</span>.log(obj.hasOwnProperty(<span class="hljs-string">"name"</span>)); <span class="hljs-comment">// true</span>
</code></pre>
<p>JavaScript doesn't block an attempt to overwrite the <code>hasOwnProperty()</code> method, which may cause an error like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = {};
obj.name = <span class="hljs-string">"Nathan"</span>;
obj.hasOwnProperty = <span class="hljs-literal">true</span>;

<span class="hljs-built_in">console</span>.log(obj.hasOwnProperty(<span class="hljs-string">"name"</span>)); 
<span class="hljs-comment">// Error: obj.hasOwnProperty is not a function</span>
</code></pre>
<p>To handle these shortcomings, JavaScript created another implementation of the Hash Table data structure which is called <code>Map</code></p>
<p>Just like <code>Object</code>, <code>Map</code> allows you to store key-value pairs inside the data structure. Here's an example of <code>Map</code> in action:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> collection = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

collection.set(<span class="hljs-string">"Nathan"</span>, <span class="hljs-string">"555-0182"</span>);
collection.set(<span class="hljs-string">"Jane"</span>, <span class="hljs-string">"555-0182"</span>);

<span class="hljs-built_in">console</span>.log(collection.get(<span class="hljs-string">"Nathan"</span>)); <span class="hljs-comment">// 555-0182</span>
<span class="hljs-built_in">console</span>.log(collection.size); <span class="hljs-comment">// 2</span>
</code></pre>
<p>Unlike the <code>Object</code> type, <code>Map</code> requires you to use the <code>set()</code> and <code>get()</code> methods to define and retrieve any key-pair values that you want to be added to the data structure. </p>
<p>You also can't overwrite <code>Map</code> inherited properties. For example, the following code tried to overwrite the <code>size</code> property value to <code>false</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> collection = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

collection.set(<span class="hljs-string">"Nathan"</span>, <span class="hljs-string">"555-0182"</span>);
collection[<span class="hljs-string">"size"</span>] = <span class="hljs-literal">false</span>;

<span class="hljs-built_in">console</span>.log(collection.get(<span class="hljs-string">"size"</span>)); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(collection.size); <span class="hljs-comment">// 1</span>
</code></pre>
<p>As you can see from the code above, you can't add a new entry to the <code>Map</code> object without using the <code>set()</code> method.</p>
<p>The <code>Map</code> data structure is also iterable, which means you can loop over the data as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

myMap.set(<span class="hljs-string">"Nathan"</span>, <span class="hljs-string">"555-0182"</span>);
myMap.set(<span class="hljs-string">"Jane"</span>, <span class="hljs-string">"315-0322"</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> [key, value] <span class="hljs-keyword">of</span> myMap) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${key}</span> = <span class="hljs-subst">${value}</span>`</span>);
}
</code></pre>
<p>Now that you've learned how JavaScript implements Hash Tables in the form of <code>Object</code> and <code>Map</code> data structures, let's see how you can create your own Hash Table implementation next.</p>
<h2 id="heading-how-to-implement-a-hash-table-data-structure-in-javascript">How to Implement a Hash Table Data Structure in JavaScript</h2>
<p>Although JavaScript already has two Hash Table implementations, writing your own Hash Table implementation is one of the most common JavaScript interview questions.</p>
<p>You can implement a Hash Table in JavaScript in three steps:</p>
<ul>
<li>Create a <code>HashTable</code> class with <code>table</code> and <code>size</code> initial properties</li>
<li>Add a <code>hash()</code> function to transform keys into indices</li>
<li>Add the <code>set()</code> and <code>get()</code> methods for adding and retrieving key/value pairs from the table.</li>
</ul>
<p>Alright, let's start with creating the <code>HashTable</code> class. The code below will create a <code>table</code> of buckets with the size of <code>127</code>:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HashTable</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">this</span>.table = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-number">127</span>);
    <span class="hljs-built_in">this</span>.size = <span class="hljs-number">0</span>;
  }
}
</code></pre>
<p>All your key/value pairs will be stored inside the <code>table</code> property.</p>
<h3 id="heading-how-to-write-the-hash-method">How to write the hash() method</h3>
<p>Next, you need to create the <code>hash()</code> method that will accept a <code>key</code> value and transform it into an index. </p>
<p>A simple way to create the hash would be to sum the ASCII code of the characters in the key using the <code>charCodeAt()</code> method as follows. Note that the method is named using <code>_</code> to indicate that it's a private method:</p>
<pre><code class="lang-js">_hash(key) {
  <span class="hljs-keyword">let</span> hash = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; key.length; i++) {
    hash += key.charCodeAt(i);
  }
  <span class="hljs-keyword">return</span> hash;
}
</code></pre>
<p>But since the <code>HashTable</code> class only has 127 buckets, this means that the <code>_hash()</code> method must return a number between <code>0 and 127</code>.</p>
<p>To ensure that the hash value doesn't exceed the bucket size, you need to use the modulo operator as shown below:</p>
<pre><code class="lang-js">_hash(key) {
  <span class="hljs-keyword">let</span> hash = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; key.length; i++) {
    hash += key.charCodeAt(i);
  }
  <span class="hljs-keyword">return</span> hash % <span class="hljs-built_in">this</span>.table.length;
}
</code></pre>
<p> Now that you have the <code>_hash()</code> method completed, it's time to write the <code>set()</code> and <code>get()</code> methods.</p>
<h3 id="heading-how-to-write-the-set-method">How to write the set() method</h3>
<p>To set the key/value pair in your Hash Table, you need to write a <code>set()</code> method that accepts  <code>(key, value)</code> as its parameters:</p>
<ul>
<li>The <code>set()</code> method will call the <code>_hash()</code> method to get the <code>index</code> value. </li>
<li>The <code>[key, value]</code> pair will be assigned to the <code>table</code> at the specified <code>index</code></li>
<li>Then, the <code>size</code> property will be incremented by one</li>
</ul>
<pre><code class="lang-js">set(key, value) {
  <span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>._hash(key);
  <span class="hljs-built_in">this</span>.table[index] = [key, value];
  <span class="hljs-built_in">this</span>.size++;
}
</code></pre>
<p>Now that the <code>set()</code> method is complete, let's write the <code>get()</code> method to retrieve a value by its key.</p>
<h3 id="heading-how-to-write-the-get-method">How to write the get() method</h3>
<p>To get a certain value from the Hash Table, you need to write a <code>get()</code> method that accepts a <code>key</code> value as its parameter:</p>
<ul>
<li>The method will call the <code>_hash()</code> method to once again retrieve the table <code>index</code></li>
<li>Return the value stored at <code>table[index]</code></li>
</ul>
<pre><code class="lang-js">get(key) {
  <span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>._hash(key);
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.table[index];
}
</code></pre>
<p>This way, the <code>get()</code> method will return either the key/value pair back or <code>undefined</code> when there is no key/value pair stored in the specified <code>index</code>.</p>
<p>So far so good. Let's add another method to delete key/value pair from the Hash Table next.</p>
<h3 id="heading-how-to-write-the-remove-method">How to write the remove() method</h3>
<p>To delete a key/value pair from the Hash Table, you need to write a <code>remove()</code> method that accepts a <code>key</code> value as its parameter:</p>
<ul>
<li>Retrieve the right <code>index</code> using the <code>_hash()</code> method</li>
<li>Check if the <code>table[index]</code> has a truthy value and the <code>length</code> property is greater than zero. Assign the <code>undefined</code> value to the right <code>index</code> and decrement the <code>size</code> property by one if it is.</li>
<li>If not, simply return <code>false</code></li>
</ul>
<pre><code class="lang-js">remove(key) {
  <span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>._hash(key);

  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[index] &amp;&amp; <span class="hljs-built_in">this</span>.table[index].length) {
    <span class="hljs-built_in">this</span>.table[index] = <span class="hljs-literal">undefined</span>;
    <span class="hljs-built_in">this</span>.size--;
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}
</code></pre>
<p>With that, you now have a working <code>remove()</code> method. Let's see if the <code>HashTable</code> class works properly.</p>
<h2 id="heading-how-to-test-the-hash-table-implementation">How to Test the Hash Table Implementation</h2>
<p>It's time to test the Hash Table implementation. Here's the full code for the Hash Table implementation again:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HashTable</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">this</span>.table = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-number">127</span>);
    <span class="hljs-built_in">this</span>.size = <span class="hljs-number">0</span>;
  }

  _hash(key) {
    <span class="hljs-keyword">let</span> hash = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; key.length; i++) {
      hash += key.charCodeAt(i);
    }
    <span class="hljs-keyword">return</span> hash % <span class="hljs-built_in">this</span>.table.length;
  }

  set(key, value) {
    <span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>._hash(key);
    <span class="hljs-built_in">this</span>.table[index] = [key, value];
    <span class="hljs-built_in">this</span>.size++;
  }

  get(key) {
    <span class="hljs-keyword">const</span> target = <span class="hljs-built_in">this</span>._hash(key);
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.table[target];
  }

  remove(key) {
    <span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>._hash(key);

    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[index] &amp;&amp; <span class="hljs-built_in">this</span>.table[index].length) {
      <span class="hljs-built_in">this</span>.table[index] = [];
      <span class="hljs-built_in">this</span>.size--;
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
  }
}
</code></pre>
<p>To test the <code>HashTable</code> class, I'm going to create a new instance of the <code>class</code> and set some key/value pairs as shown below. The key/value pairs below are just arbitrary number values paired with country names without any special meaning:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ht = <span class="hljs-keyword">new</span> HashTable();
ht.set(<span class="hljs-string">"Canada"</span>, <span class="hljs-number">300</span>);
ht.set(<span class="hljs-string">"France"</span>, <span class="hljs-number">100</span>);
ht.set(<span class="hljs-string">"Spain"</span>, <span class="hljs-number">110</span>);
</code></pre>
<p>Then, let's try to retrieve them using the <code>get()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(ht.get(<span class="hljs-string">"Canada"</span>)); <span class="hljs-comment">// [ 'Canada', 300 ]</span>
<span class="hljs-built_in">console</span>.log(ht.get(<span class="hljs-string">"France"</span>)); <span class="hljs-comment">// [ 'France', 100 ]</span>
<span class="hljs-built_in">console</span>.log(ht.get(<span class="hljs-string">"Spain"</span>)); <span class="hljs-comment">// [ 'Spain', 110 ]</span>
</code></pre>
<p>Finally, let's try to delete one of these values with the <code>remove()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(ht.remove(<span class="hljs-string">"Spain"</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(ht.get(<span class="hljs-string">"Spain"</span>)); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>Alright, all the methods are working as expected. Let's try another insertion with a new <code>HashTable</code> instance and retrieve those values:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ht = <span class="hljs-keyword">new</span> HashTable();

ht.set(<span class="hljs-string">"Spain"</span>, <span class="hljs-number">110</span>);
ht.set(<span class="hljs-string">"ǻ"</span>, <span class="hljs-number">192</span>);

<span class="hljs-built_in">console</span>.log(ht.get(<span class="hljs-string">"Spain"</span>)); <span class="hljs-comment">// [ 'ǻ', 192 ]</span>
<span class="hljs-built_in">console</span>.log(ht.get(<span class="hljs-string">"ǻ"</span>)); <span class="hljs-comment">// [ 'ǻ', 192 ]</span>
</code></pre>
<p>Oops! Looks like we got into some trouble here. 😨</p>
<h2 id="heading-how-to-handle-index-collision">How to Handle Index Collision</h2>
<p>Sometimes, the hash function in a Hash Table may return the same <code>index</code> number. In the test case above, the string <code>"Spain"</code> and <code>"ǻ"</code> <strong>both return the same <code>hash</code> value</strong> because the number <code>507</code> is the sum of both of their ASCII code.</p>
<p>The same <code>hash</code> value will cause the index to <em>collide</em>, overwriting the previous entry with the new one.</p>
<p>Right now, the data stored in our Hash Table implementation looks as follows:</p>
<pre><code class="lang-js">[
    [ <span class="hljs-string">"Spain"</span>, <span class="hljs-number">110</span>],
    [ <span class="hljs-string">"France"</span>, <span class="hljs-number">100</span>]
]
</code></pre>
<p>To handle the <code>index</code> number collision, you need to store the key/value pair in a second array so that the end result looks as follows:</p>
<pre><code class="lang-js">[
    [
        [ <span class="hljs-string">"Spain"</span>, <span class="hljs-number">110</span> ],
        [ <span class="hljs-string">"ǻ"</span>, <span class="hljs-number">192</span> ]
    ],
    [
        [<span class="hljs-string">"France"</span>, <span class="hljs-number">100</span>]
    ],
]
</code></pre>
<p>To create the second array, you need to update the <code>set()</code> method so that it will:</p>
<ul>
<li>Look to the <code>table[index]</code> and loop over the array values.</li>
<li>If the key at one of the arrays is equal to the <code>key</code> passed to the method, replace the value at index <code>1</code> and stop any further execution with the <code>return</code> statement.</li>
<li>If no matching <code>key</code> is found, push a new array of key and value to the second array.</li>
<li>Else, initialize a new array and push the key/value pair to the specified <code>index</code></li>
<li>Whenever a <code>push()</code> method is called, increment the <code>size</code> property by one.</li>
</ul>
<p>The complete <code>set()</code> method code will be as follows:</p>
<pre><code class="lang-js">set(key, value) {
  <span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>._hash(key);
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[index]) {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.table[index].length; i++) {
      <span class="hljs-comment">// Find the key/value pair in the chain</span>
      <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[index][i][<span class="hljs-number">0</span>] === key) {
        <span class="hljs-built_in">this</span>.table[index][i][<span class="hljs-number">1</span>] = value;
        <span class="hljs-keyword">return</span>;
      }
    }
    <span class="hljs-comment">// not found, push a new key/value pair</span>
    <span class="hljs-built_in">this</span>.table[index].push([key, value]);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">this</span>.table[index] = [];
    <span class="hljs-built_in">this</span>.table[index].push([key, value]);
  }
  <span class="hljs-built_in">this</span>.size++;
}
</code></pre>
<p>Next, update the <code>get()</code> method so that it will also check the second-level array with a <code>for</code> loop and return the right key/value pair:</p>
<pre><code class="lang-js">get(key) {
  <span class="hljs-keyword">const</span> target = <span class="hljs-built_in">this</span>._hash(key);
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[target]) {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.table.length; i++) {
      <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[target][i][<span class="hljs-number">0</span>] === key) {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.table[target][i][<span class="hljs-number">1</span>];
      }
    }
  }
  <span class="hljs-keyword">return</span> <span class="hljs-literal">undefined</span>;
}
</code></pre>
<p>Finally, you need to update the <code>remove()</code> method so that it will loop over the second-level array and remove the array with the right <code>key</code> value using the <code>splice()</code> method:</p>
<pre><code class="lang-js">remove(key) {
  <span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>._hash(key);

  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[index] &amp;&amp; <span class="hljs-built_in">this</span>.table[index].length) {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.table.length; i++) {
      <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[index][i][<span class="hljs-number">0</span>] === key) {
        <span class="hljs-built_in">this</span>.table[index].splice(i, <span class="hljs-number">1</span>);
        <span class="hljs-built_in">this</span>.size--;
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
      }
    }
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}
</code></pre>
<p>With that, your <code>HashTable</code> class will be able to avoid any index number collision and store the key/value pair inside the second-level array.</p>
<p>As a bonus, let's add a <code>display()</code> method that will display all key/value pairs stored in the Hash Table. You just need to use the <code>forEach()</code> method to iterate over the table and <code>map()</code> the values to a string as shown below:</p>
<pre><code class="lang-js">display() {
  <span class="hljs-built_in">this</span>.table.forEach(<span class="hljs-function">(<span class="hljs-params">values, index</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> chainedValues = values.map(
      <span class="hljs-function">(<span class="hljs-params">[key, value]</span>) =&gt;</span> <span class="hljs-string">`[ <span class="hljs-subst">${key}</span>: <span class="hljs-subst">${value}</span> ]`</span>
    );
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${index}</span>: <span class="hljs-subst">${chainedValues}</span>`</span>);
  });
}
</code></pre>
<p>Here's the complete <code>HashTable</code> class code again with the collision avoidance applied for your reference:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HashTable</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">this</span>.table = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-number">127</span>);
    <span class="hljs-built_in">this</span>.size = <span class="hljs-number">0</span>;
  }

  _hash(key) {
    <span class="hljs-keyword">let</span> hash = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; key.length; i++) {
      hash += key.charCodeAt(i);
    }
    <span class="hljs-keyword">return</span> hash % <span class="hljs-built_in">this</span>.table.length;
  }

  set(key, value) {
    <span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>._hash(key);
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[index]) {
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.table[index].length; i++) {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[index][i][<span class="hljs-number">0</span>] === key) {
          <span class="hljs-built_in">this</span>.table[index][i][<span class="hljs-number">1</span>] = value;
          <span class="hljs-keyword">return</span>;
        }
      }
      <span class="hljs-built_in">this</span>.table[index].push([key, value]);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">this</span>.table[index] = [];
      <span class="hljs-built_in">this</span>.table[index].push([key, value]);
    }
    <span class="hljs-built_in">this</span>.size++;
  }

  get(key) {
    <span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>._hash(key);
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[index]) {
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.table.length; i++) {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[index][i][<span class="hljs-number">0</span>] === key) {
          <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.table[index][i][<span class="hljs-number">1</span>];
        }
      }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">undefined</span>;
  }

  remove(key) {
    <span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>._hash(key);

    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[index] &amp;&amp; <span class="hljs-built_in">this</span>.table[index].length) {
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.table.length; i++) {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.table[index][i][<span class="hljs-number">0</span>] === key) {
          <span class="hljs-built_in">this</span>.table[index].splice(i, <span class="hljs-number">1</span>);
          <span class="hljs-built_in">this</span>.size--;
          <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
        }
      }
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
  }

  display() {
    <span class="hljs-built_in">this</span>.table.forEach(<span class="hljs-function">(<span class="hljs-params">values, index</span>) =&gt;</span> {
      <span class="hljs-keyword">const</span> chainedValues = values.map(
        <span class="hljs-function">(<span class="hljs-params">[key, value]</span>) =&gt;</span> <span class="hljs-string">`[ <span class="hljs-subst">${key}</span>: <span class="hljs-subst">${value}</span> ]`</span>
      );
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${index}</span>: <span class="hljs-subst">${chainedValues}</span>`</span>);
    });
  }
}
</code></pre>
<p>You can test the implementation by creating a new <code>HashTable</code> instance and do some insertion and deletion:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ht = <span class="hljs-keyword">new</span> HashTable();

ht.set(<span class="hljs-string">"France"</span>, <span class="hljs-number">111</span>);
ht.set(<span class="hljs-string">"Spain"</span>, <span class="hljs-number">150</span>);
ht.set(<span class="hljs-string">"ǻ"</span>, <span class="hljs-number">192</span>);

ht.display();
<span class="hljs-comment">// 83: [ France: 111 ]</span>
<span class="hljs-comment">// 126: [ Spain: 150 ],[ ǻ: 192 ]</span>

<span class="hljs-built_in">console</span>.log(ht.size); <span class="hljs-comment">// 3</span>
ht.remove(<span class="hljs-string">"Spain"</span>);
ht.display();
<span class="hljs-comment">// 83: [ France: 111 ]</span>
<span class="hljs-comment">// 126: [ ǻ: 192 ]</span>
</code></pre>
<p>Now there's no collision inside the <code>HashTable</code> instance. Great work!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you've learned what a Hash Table is and how JavaScript uses it to create the <code>Object</code> and <code>Map</code> data structure.</p>
<p>You've also learned how to implement your own <code>HashTable</code> class as well as how to prevent the Hash Table's key indices from colliding by using the chaining technique.</p>
<p>By using a Hash Table data structure, you will be able to create an associative array with fast search, insertion, and delete operations. 😉</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G">here</a>.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Codeless Guide to Hashing and Hash Tables ]]>
                </title>
                <description>
                    <![CDATA[ By Armstrong Subero If you have programmed before, you are sure to have come across hashing and hash tables. Many developers have used hash tables in one form or another, and beginner developers must learn this fundamental data structure. There is ju... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-codeless-guide-to-hash/</link>
                <guid isPermaLink="false">66d45d9c787a2a3b05af437e</guid>
                
                    <category>
                        <![CDATA[ cybersecurity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Hash tables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 06 Mar 2020 16:47:50 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9c45740569d1a4ca3116.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Armstrong Subero</p>
<p>If you have programmed before, you are sure to have come across hashing and hash tables. Many developers have used hash tables in one form or another, and beginner developers must learn this fundamental data structure. There is just one problem:</p>
<p><strong>All the tutorials you come across are sure to discuss hashing and hash tables in JavaScript, Python, or some other programming language.</strong> </p>
<p>What this means is that you may understand a little about how hashing works and how to use a hash table in [insert language here], but may miss the principles of how it works.</p>
<p>Wouldn't it be great if we could learn about hashing without knowing any particular language? If you know how hashing works, and what a hash table is, the language shouldn't matter. </p>
<p>That is the codeless approach, and in this post I will teach you all about hashing and hash tables regardless of which programming language you are currently using. Whether you're a junior or senior dev, everyone will learn something from this post. </p>
<h2 id="heading-so-whats-a-hash-function-anyway">So What's a Hash Function Anyway?</h2>
<p>Before we get into all the fancy stuff, let me tell you what hashing is. To make it easy let's imagine we have a black box:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/image.png" alt="Image" width="600" height="400" loading="lazy">
<em>I'm a Black Box</em></p>
<p>This black box is special. It is called a function box. We'll call it a function box because this box will map an independent variable on the input to a dependent variable on the output (it sounds mathy but bear with me). </p>
<p>Our function box works like this: if we put a letter into the box, we get a number out. Since our box is a function box, there can only be one output for every input into the box.</p>
<p>Our function box will take a letter from A-J on the input and output a corresponding number from 0 to 9 on the output. So if we input C we will get 2 on the output.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/image-3.png" alt="Image" width="600" height="400" loading="lazy">
<em>Function Box</em></p>
<p>This forms the basics of what a hash function is. The hash function, however, takes it a step further. We will map data on the input to some numeric value on the output, usually a hexadecimal sequence. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/image-4.png" alt="Image" width="600" height="400" loading="lazy">
<em>Hash Function</em></p>
<p>So essentially all hashing does is it uses a function to map data to a representative numeric or alphanumeric value. For the hash function, regardless of the size of the input, the output will always remain the same. </p>
<h2 id="heading-what-about-hash-tables">What about Hash Tables?</h2>
<p>So at this point you may be wondering what a hash table is. Hash tables utilize hashing to form a data structure. </p>
<p>Hash tables use an associative method to store data by using what is known as a key-value lookup system. All that means is that, in a hash table, keys are mapped to unique values.</p>
<p>This system of organizing data results in a very fast way to find data efficiently. This is because since each key is mapped to a unique value – once we know a key then we can find the associated value instantly. </p>
<p>Hash tables are extremely fast, having a time complexity that is in the order of O(1). </p>
<p>Confused? Take a look at this diagram, where we have multiple function boxes generating hash values.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/image-5.png" alt="Image" width="600" height="400" loading="lazy">
<em>Multiple Function Boxes</em></p>
<p>In this scenario, each character on the input (each is a key) has a hash function applied to it, and the hash function in the function box generates the hash value. This resulting value is then mapped to an index in the underlying linked list or array used to implement the hash table. </p>
<p>The resulting structure will look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/hashtable.png" alt="Image" width="600" height="400" loading="lazy">
<em>Hash Table</em></p>
<h2 id="heading-hash-collisions">Hash Collisions</h2>
<p>This is a good time to talk about collision in hash functions and hash tables. </p>
<p>A function in mathematics is ideal in that an element in the input is mapped to exactly one element in the output. </p>
<p>In a hash function, however, it is not always like this. Sometimes differing hash values in the input may produce the same hash value in the output. When this occurs you get what is known as a hash collision. </p>
<p>Hash collisions are not very common in most use cases, as a small change in the input can produce a dramatically differing output. But the more data you have to input to the hash function, the more likely a collision is to occur. </p>
<p>In the hash table example we provided earlier, we assumed that an array was used to implement the hash table. While this is good for simple hash tables, in practice these are not very good for handling collisions. </p>
<p>As such, a method known as chaining is used. In chaining, if the hash table returns the same hash value for multiple elements, we simply "chain" the elements together with the same hash values at the same index in the hash table.  </p>
<p>This way instead of being implemented as an array with an index, we implement the hash table using a linked list where each element is a list rather than merely having a single value assigned to it. </p>
<p>But as the length of the chain increases, the time complexity of the hash table can get worse. A method known as open addressing is also used. In it, alternate locations in the underlying data structure implementing the hash table are found. Just keep in mind that this method will reduce the efficiency of the hash table and has a worse time complexity.</p>
<h2 id="heading-is-hashing-the-same-as-encryption-or-encoding">Is Hashing the Same as Encryption or Encoding?</h2>
<p>Many people tend to associate hashing with encryption or encoding. So is hashing encryption? Is it the same as encoding? </p>
<p>You see, in encryption we muddle data so that only someone with the key needed to decrypt the data will have access to it. When we utilize an encryption cipher, we not only make the data encrypted, but we also want to decrypt the data at some point. In encryption we want to recover the original data. </p>
<p>Hashing, on the other hand, takes data and produces an output for the purpose of confirming the integrity of data. In hashing we have no intention of recovering the original data. </p>
<p>Encoding differs from encryption and hashing in that the goal of encoding is not to obscure data for any security purpose, but merely to convert the data into a format that another system can use. </p>
<h2 id="heading-what-can-i-do-with-hashing">What Can I Do with Hashing?</h2>
<p>Hashes and hash tables have numerous uses! These include:</p>
<ol>
<li>Cryptosystems</li>
<li>Cyclic Redundancy Checks</li>
<li>Search Engines</li>
<li>Databases</li>
<li>Compilers</li>
</ol>
<p>Or any system that has a complex lookup process.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this post we've covered the basics of hashing, all without writing a single line of code! This was easy right? The codeless approach is a much easier way of learning about these fundamental topics. </p>
<p>We learned that hash functions can be used to convert objects into a fixed length alphanumeric output. We also learned that hash tables are key-value lookup systems and, while they work well, are not perfect and sometimes suffer from collisions.</p>
<p>By the end of this post you should know the difference between hashing, encryption, and encoding, and also have an idea of where hashes can be used. </p>
<p>Did you like the codeless approach? Want to go further?</p>
<p>Learn about hash tables and other data structures and algorithms in the book "Codeless Data Structures and Algorithms". You'll get an expansion of what was covered in this post and learn about many more topics, all without writing a single line of code!</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.apress.com/gp/book/9781484257241">https://www.apress.com/gp/book/9781484257241</a></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Hashing? How Hash Codes Work - with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Introduction to hashing Hashing is designed to solve the problem of needing to efficiently find or store an item in a collection. For example, if we have a list of 10,000 words of English and we want to check if a given word is in the list, it would ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-hashing/</link>
                <guid isPermaLink="false">66c365a98e244e167873862c</guid>
                
                    <category>
                        <![CDATA[ Hash tables ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 26 Jan 2020 22:44:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9d75740569d1a4ca37e1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-introduction-to-hashing">Introduction to hashing</h2>
<p>Hashing is designed to solve the problem of needing to efficiently find or store an item in a collection.</p>
<p>For example, if we have a list of 10,000 words of English and we want to check if a given word is in the list, it would be inefficient to successively compare the word with all 10,000 items until we find a match. Even if the list of words are lexicographically sorted, like in a dictionary, you will still need some time to find the word you are looking for.</p>
<p>Hashing is a technique to make things more efficient by effectively narrowing down the search at the outset.</p>
<h2 id="heading-what-is-hashing"><strong>What is hashing?</strong></h2>
<p>Hashing means using some function or algorithm to map object data to some representative integer value.</p>
<p>This so-called hash code (or simply hash) can then be used as a way to narrow down our search when looking for the item in the map.</p>
<p>Generally, these hash codes are used to generate an index, at which the value is stored.</p>
<h2 id="heading-how-hashing-works"><strong>How hashing works</strong></h2>
<p>In hash tables, you store data in forms of key and value pairs. The key, which is used to identify the data, is given as an input to the hashing function. The hash code, which is an integer, is then mapped to the fixed size we have.</p>
<p>Hash tables have to support 3 functions.</p>
<ul>
<li>insert (key, value)</li>
<li>get (key)</li>
<li>delete (key)</li>
</ul>
<p>Purely as an example to help us grasp the concept, let us suppose that we want to map a list of string keys to string values (for example, map a list of countries to their capital cities).</p>
<p>So let’s say we want to store the data in Table in the map.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-15-at-2.53.40-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And let us suppose that our hash function is to simply take the length of the string.</p>
<p>For simplicity, we will have two arrays: one for our keys and one for the values.<br>So to put an item in the hash table, we compute its hash code (in this case, simply count the number of characters), then put the key and value in the arrays at the corresponding index.</p>
<p>For example, Cuba has a hash code (length) of 4. So we store Cuba in the 4th position in the keys array, and Havana in the 4th index of the values array etc. And we end up with the following:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-15-at-2.54.43-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now, in this specific example things work quite well. Our array needs to be big enough to accommodate the longest string, but in this case that’s only 11 slots.<br>We do waste a bit of space because, for example, there are no 1-letter keys in our data, nor keys between 8 and 10 letters. </p>
<p>But in this case, the wasted space isn’t so bad either. Taking the length of a string is nice and fast, and so is the process of finding the value associated with a given key (certainly faster than doing up to five string comparisons).</p>
<p>But, what do we do if our dataset has a string which has more than 11 characters?<br>What if we have one another word with 5 characters, “India”, and try assigning it to an index using our hash function. Since the index 5 is already occupied, we have to make a call on what to do with it. This is called a collision.</p>
<p>If our dataset had a string with thousand characters, and you make an array of thousand indices to store the data, it would result in a wastage of space. If our keys were random words from English, where there are so many words with same length, using length as a hashing function would be fairly useless.</p>
<h2 id="heading-collision-handling"><strong>Collision Handling</strong></h2>
<p>Two basic methods are used to handle collisions.</p>
<ol>
<li>Separate Chaining</li>
<li>Open Addressing</li>
</ol>
<h3 id="heading-separate-chaining">Separate Chaining</h3>
<p>Hash collision handling by separate chaining, uses an additional data structure, preferrably linked list for dynamic allocation, into buckets. In our example, when we add India to the dataset, it is appended to the linked list stored at the index 5, then our table would look like this.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/03/Screen-Shot-2020-03-15-at-2.55.47-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To find an item we first go to the bucket and then compare keys. This is a popular method, and if a list of links is used the hash never fills up. The cost for <code>get(k)</code> is on average <code>O(n)</code> where n is the number of keys in the bucket, total number of keys be N.</p>
<p>The problem with separate chaining is that the data structure can grow with out bounds.</p>
<h3 id="heading-open-addressing">Open Addressing</h3>
<p>Open addressing does not introduce any new data structure. If a collision occurs then we look for availability in the next spot generated by an algorithm. Open Addressing is generally used where storage space is a restricted, i.e. embedded processors. Open addressing not necessarily faster then separate chaining.</p>
<p>Methods for Open Addressing</p>
<ul>
<li>[Linear Probing</li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Quadratic_probing">Quadratic Probing</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Double_hashing">Double Hashing</a></li>
</ul>
<h2 id="heading-how-to-use-hashing-in-your-code"><strong>How to use hashing in your code.</strong></h2>
<h4 id="heading-python"><strong>Python</strong></h4>
<pre><code class="lang-text">   # Few languages like Python, Ruby come with an in-built hashing support.
   # Declaration
    my_hash_table = {}
    my_hash_table = dict()

   # Insertion
    my_hash_table[key] = value

   # Look up
    value = my_hash_table.get(key) # returns None if the key is not present || Deferred in python 3, available in python 2
    value = my_hash_table[key] # throws a ValueError exception if the key is not present

    # Deletion
    del my_hash_table[key] # throws a ValueError exception if the key is not present

    # Getting all keys and values stored in the dictionary
    keys = my_hash_table.keys()
    values = my_hash_table.values()
</code></pre>
<p><img src="https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2" alt=":rocket:" width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://repl.it/CVtK">Run Code</a></p>
<h4 id="heading-java"><strong>Java</strong></h4>
<pre><code class="lang-text">    // Java doesn't include hashing by default, you have to import it from java.util library
    // Importing hashmaps
    import java.util.HashMap;

   // Declaration
    HashMap&lt;Integer, Integer&gt; myHashTable = new HashMap&lt;Integer, Integer&gt;(); // declares an empty map.

   // Insertion
    myHashTable.put(key, value);

   // Deletion
    myHashtable.remove(key);

    // Look up
    myHashTable.get(key); // returns null if the key K is not present
    myHashTable.containsKey(key); // returns a boolean value, indicating the presence of a key

    // Number of key, value pairs in the hash table
    myHashTable.size();
</code></pre>
<p><img src="https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2" alt=":rocket:" width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://repl.it/CVt1">Run Code</a></p>
<h2 id="heading-more-info-on-hashing">More info on hashing</h2>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/the-codeless-guide-to-hash/">The codeless guide to hashing and hash tables</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-implement-a-simple-hash-table-in-javascript-cb3b9c1f2997/">How to implement a simple hash table in JavaScript</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/hash-tables/">Hash tables explained</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
