πŸ“’
SDV503
  • SDV503
  • Command Prompt
    • Windows Command Prompt
    • Mac OS Terminal
  • GIT & GITHub
    • GitHub
    • Git
      • Git Workflow
        • Forking Workflow
  • README
    • How to write a readme.md file?
    • Write a better README.me
    • Generate a README for GitHub Repo Quickly
  • Code-comments
    • Clean Comments
    • Writing Comments in a Good way
  • Pair Coding
    • What is Pair Coding?
    • Pair Programming Experience
  • Programming?
    • What is Programming?
    • What Is A Programming Paradigm?
    • JavaScript Programming Paradigms
  • Number Systems
    • Decimal and Binary numbers
  • JavaSCript
    • Introduction To JavaScript
      • The JavaScript Engine
  • JS Call Stack
    • JavaScript call stack
    • JavaScript & Memory
      • Memory Leaks in JavaScript
    • Execution Context and Execution Stack in Javascript
      • Javascript Execution Context and Hoisting
  • JavaScript Variables
    • Introduction to JS Data Types
    • Primitive and Non-Primitive
    • Operator precedence and associativity
      • JS Operators Part One
      • JS Operators Part Two
      • JS Operators Part Three
    • Clean Code for JS Variables
  • JavaScript Scopes
    • Scope (Chain) Visualized
  • Javascript β€Šβ€”β€Šthis keyword
  • JavaScript Data Types
    • More JavaScript Data Types
  • JavaScript Expressions and Statements
  • if/else, switch and ternary operator
    • If/Else statement
  • Switch Statement
  • Ternary Operator
  • JavaScript Loops
    • Loops in JavaScript
      • Trouble With Loops
  • Objects
    • JavaScript Objects
      • Prototypal Inheritance Visualized
      • JavaScript Number Object
      • JavaScript String Object
  • Functions
    • JavaScript Function Part One
    • JavaScript Function Part Two
    • Immediately Invoked Function Expressions ~ IIFE
    • JS => Arrow Functions
    • JavaScript Callback
    • Hoisting in JavaScript
      • Hoisting Visualized
    • Recursion Functions
    • Curry and Function Composition
  • JavaScript Features
    • JSpread Operator
    • JavaScript Built-in Functions & Objects
  • Data Structures&Algorithms
    • JavaScript’s Data Types
    • Data Structures in JavaScript
      • Introduction to Big O Notation
      • Big O Notation in Javascript
      • Linked Lists
        • Linked Lists β€” 2
      • Hash Tables
      • Stack & Queue
  • TLDR
    • Single quotes (β€˜ ’) and double quotes (β€œ ”) in JavaScript
  • ES6
    • Generators and Iterators
    • Javascript Classes
    • JavaScript closures
    • JavaScript Promises & Async/Await
      • Event Loop Visualized
  • C#
    • What does C#? (C Sharp)
    • C# vs JavaScript
    • What Is The Difference Between C#, .NET, ASP.NET, Microsoft.NET, and Visual Studio?
    • What is the .NET Framework?
    • Methods and Properties of Console Class in C#
    • Datatypes in C#
    • C# Code Comments
    • The if statement
    • The switch statement
    • Loops
    • Comparison operators
    • Addition assignment operators
    • The String Interpolation Operator
    • Arrays
    • Lists
    • Dictionaries
Powered by GitBook
On this page
  • Lets’ begin!!
  • Core
  • ⚜️ The list
  • πŸ”… Put
  • πŸ”… Remove
  • πŸ”… Search & Size
  • πŸ”… IsEmpty
  • It’s just the beginning with hash tables…
  • Let us see the real issue with Hash Functions β€”
  • Hash Tables β€” Separate Chaining Method
  • Core
  • ⚜️ The list
  • Lets write some lines of code now.. πŸ€“
  • πŸ”… Put
  • πŸ”… Remove
  • πŸ”… Contains
  • πŸ”… Size & IsEmpty
  • πŸ”… Traverse
  • Practice

Was this helpful?

  1. Data Structures&Algorithms
  2. Data Structures in JavaScript

Hash Tables

PreviousLinked Lists β€” 2NextStack & Queue

Last updated 5 years ago

Was this helpful?

Hash tables is a data structure in which every value is associated with a key and we can find that key using hash function.

⚠️ Read more about the basics of Hashing and Hash tables.

❗️All the code snippets you will see below are just Pseudo code.

Lets’ begin!!

Core

⚜️ The list

  1. Put

  2. Remove

  3. Search

  4. Size

  5. IsEmpty

Initial Hash table

πŸ”… Put

put( item ) {
  let key = this.computeHash( item )
  return !this.table[key] ? this.table[key] = item : false;
}

Put Operation

πŸ”… Remove

remove( item ) {
  let key = this.computeHash( item )
  return this.table[key] = undefined
}

Remove Operation

πŸ”… Search & Size

search( item ) {
  let key = this.computeHash( item )
  return this.table[key] === item
}size() {
  let counter = 0;
  for( let i=0, len = this.table.length; i < len; i++) {
   if( this.table[i] ) { counter++ }
  }
  return counter;
}

❗️The technique which I am using to find out size is very time consuming. This is one way but the better one will be to use a counter for size. Just increment that counter whenever we put an item in Hash table and decrement it when we delete an item. Just return that counter in the size function so that we do not have to iterate over whole Hash Table very time we call it ( Some geek pointed this on reddit thread… thank you) and in next post I will implement this.

Then why are you still using it here ? I am still using this because you can use this piece of code for a lot of other things i.e you can use this to traverse over whole Hash Table and implement a function ( may be by some reason you want every value to be in a lowercase or uppercase) over each item which will help you do a lot of other things when you are practicing this. So, this code is just to show that this is one way to do this but as I mentioned that this is not one of the best way to this sort of work. Use pointers instead.

Search & Size Operation

πŸ”… IsEmpty

isEmpty() {
  for( let i=0, len = this.table.length; i < len; i++) {
   if( this.table[i] ) { return false };
  }
  return true
}

IsEmpty Operation

It’s just the beginning with hash tables…

Let us see the real issue with Hash Functions β€”

In the example above, I am using a very simple Hash Function which is β€”

computeHash( string ) {
  let H = this.findPrime( this.table.length )
  let total = 0;
  for (let i = 0; i < string.length; ++i) {
    total += H * total + string.charCodeAt(i)
  }
  return total % this.table.length
}

⚠️ In the function above, I am using a prime number. I know a lot of you are scratching their heads that why I used this. Well, it is playing a great role here.

There are a lot of ways you can design your own Hash Functions but no matter how complex you make you Hash Function but there is always high possibility that they will face one issue and that is β€”

🀜 Hash Table Collisions πŸ€›

…means when Hash Function returns same hash for more than one values.

There are various solutions to this problem β€”

  • Separate Chaining, etc…

but in this post, we will go through one of major of them β€” Separate chaining.

Hash Tables β€” Separate Chaining Method

In this method, the hash table will contain links to linked-lists and we will search and insert the item by iterating over these linked-lists.

Core

⚜️ The list

  1. Put

  2. Remove

  3. Contains

  4. Size

  5. IsEmpty

  6. Traverse

Lets write some lines of code now.. πŸ€“

Hash Table before all operations

πŸ”… Put

put( item ) {
   let key = this.computeHash( item )
   let node = new Node(item)
   if ( this.table[key] ) {
     node.next = this.table[key]
   }
   this.table[key] = node
}

Put Operation

πŸ”… Remove

remove( item ) {
  let key = this.computeHash( item )
  if( this.table[key] ) {
     if( this.table[key].data === item ) {
        this.table[key] = this.table[key].next
     } else {
       let current = this.table[key].next
       let prev = this.table[key]
       while( current ) {
         if( current.data === item ) {
           prev.next = current.next
         }
         prev = current
         current = current.next
       }
     }
  }
}

Remove Operation

πŸ”… Contains

contains( item ) {
  for(let i=0; i<this.table.length; i++){
    if( this.table[i] ) {
      let current = this.table[i];
      while( current ) {
        if( current.data === item ) {
          return true;
        }
        current = current.next;
      }
    }
  }
  return false;
}

Contains Opeartion

πŸ”… Size & IsEmpty

size( item ) {
  let counter = 0
  for(let i=0; i.table.length; i++){
    if( this.table[i] ) {
      let current = this.table[i]
      while( current ) {
        counter++
        current = current.next
      }
    }
  }
  return counter
}isEmpty() {
  return this.size() < 1
}

Size & IsEmpty Operation

πŸ”… Traverse

traverse( fn ) {
  for(let i=0; i.table.length; i++){
    if( this.table[i] ) {
      let current = this.table[i];
      while( current ) {
        fn( current );
        current = current.next;
      }
    }
  }
}

Practice

πŸ”Ή πŸ”Ή πŸ”Ή

Deletion in Separate Chaining Method β€”

LeetCode β€”

GeekForGeeks β€”

HackerEarth β€”

Open Addressing
Linear Probing
Quadratic Probing
Double Hashing
algs4.cs.princeton.edu
Hash Tables
Hashing Data Structures
Hash Tables
Click here