What is Hashing? How Hash Codes Work - with Examples (2024)

/ #hash tables
What is Hashing? How Hash Codes Work - with Examples (1)

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 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.

Hashing is a technique to make things more efficient by effectively narrowing down the search at the outset.

What is hashing?

Hashing means using some function or algorithm to map object data to some representative integer value.

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.

Generally, these hash codes are used to generate an index, at which the value is stored.

How hashing works

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.

Hash tables have to support 3 functions.

  • insert (key, value)
  • get (key)
  • delete (key)

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).

So let’s say we want to store the data in Table in the map.

What is Hashing? How Hash Codes Work - with Examples (2)

And let us suppose that our hash function is to simply take the length of the string.

For simplicity, we will have two arrays: one for our keys and one for the values.
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.

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:

What is Hashing? How Hash Codes Work - with Examples (3)

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.
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.

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).

But, what do we do if our dataset has a string which has more than 11 characters?
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.

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.

Collision Handling

Two basic methods are used to handle collisions.

  1. Separate Chaining
  2. Open Addressing

Separate Chaining

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.

What is Hashing? How Hash Codes Work - with Examples (4)

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 get(k) is on average O(n) where n is the number of keys in the bucket, total number of keys be N.

The problem with separate chaining is that the data structure can grow with out bounds.

Open Addressing

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.

Methods for Open Addressing

How to use hashing in your code.

Python

 # 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()
What is Hashing? How Hash Codes Work - with Examples (5)

Run Code

Java

 // Java doesn't include hashing by default, you have to import it from java.util library // Importing hashmaps import java.util.HashMap; // Declaration HashMap<Integer, Integer> myHashTable = new HashMap<Integer, Integer>(); // 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();
What is Hashing? How Hash Codes Work - with Examples (6)

Run Code

More info on hashing

  • The codeless guide to hashing and hash tables
  • How to implement a simple hash table in JavaScript
  • Hash tables explained

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

If this article was helpful, .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTIsem*nT

What is Hashing? How Hash Codes Work - with Examples (2024)

FAQs

What is Hashing? How Hash Codes Work - with Examples? ›

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 be inefficient to successively compare the word with all 10,000 items until we find a match.

What is hashing with an example? ›

Hashing is the process of transforming any given key or a string of characters into another value. This is usually represented by a shorter, fixed-length value or key that represents and makes it easier to find or employ the original string. The most popular use for hashing is the implementation of hash tables.

What is an example of a hash code? ›

For example, if the input is 123,456,789 and the hash table size 10,000, squaring the key produces 15,241,578,750,190,521, so the hash code is taken as the middle 4 digits of the 17-digit number (ignoring the high digit) 8750.

How does hashing technique work? ›

Hashing is the process of assigning a numeric value to an alphanumeric string by first converting it into another numeric value and storing it in an indexed table to make data retrieval faster and/or masking the data for encryption, performed by a hash function.

What is the meaning of Hashcode? ›

What Does Hash Code Mean? Hash code in . NET framework is a numeric value which helps in identification of an object during equality testing and also can serve as an index for the object. The value contained in the hash code is not permanent in nature.

How do you explain hashing algorithm? ›

A hashing algorithm is a mathematical function that garbles data and makes it unreadable. Hashing algorithms are one-way programs, so the text can't be unscrambled and decoded by anyone else. And that's the point.

What is a real life example of hashing function? ›

Every time you attempt to log in to your email account, your email provider hashes the password YOU enter and compares this hash to the hash it has saved. Only when the two hashes match are you authorized to access your email.

What are the three types of hashing? ›

Types of Hash functions
  • Division Method.
  • Mid Square Method.
  • Folding Method.
  • Multiplication Method.

How many digits is a hash code? ›

In cryptography, SHA-1 (Secure Hash Algorithm 1) is a hash function which takes an input and produces a 160-bit (20-byte) hash value known as a message digest – typically rendered as 40 hexadecimal digits.

Why do we need hashing? ›

Hashing is the process of using a mathematical function to convert input data into a fixed-length output. Businesses use hashing functions to ensure that the data stored on servers and cloud storage systems remain unreadable even if malicious hackers gain access to the data.

How do you write a good hash code? ›

Rules for choosing good hash function:
  1. The hash function should be simple to compute.
  2. Number of collisions should be less while placing the record in the hash table. ...
  3. Hash function should produce such keys which will get distributed uniformly over an array.
  4. The hash function should depend on every bit of the key.
Feb 21, 2023

How does hashing work mathematically? ›

A hash function is a mathematical function or algorithm that simply takes a variable number of characters (called a ”message”) and converts it into a string with a fixed number of characters (called a hash value or simply, a hash).

What is the difference between hashing and encryption? ›

Basically, encryption is the process of scrambling plaintext into unreadable ciphertext, which you can decrypt with a relevant key, while hashing turns plain text into a unique code, which can't be reverted into a readable form.

How many keys does hashing require? ›

The basic operation of hash functions does not need any key and operate in a one-way manner. The one-way operation means that it is impossible to compute the input from a particular output. The basic uses of hash functions are: Generation and verification of digital signatures.

How do hash codes work? ›

Hashing means using some function or algorithm to map object data to some representative integer value. 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.

How to generate hashCode? ›

The use of the bit-wise xor operator, " ^ ", then combines the last 32 bits of the long value with the first 32 bits of the long value. The operation of constructing the hash code is shown below for the long value x = 1234567890098765432L .

Why do we need hashCode? ›

The hashCode() method is used to generate the hash values of objects. Using these hash values, these objects are stored in Java collections such as HashMap, HashSet and HashTable.

What is an example of hashed data? ›

Hashing can turn PII (such as the name “John” or an SSN) into an indecipherable but uniform string of characters. For example, using the SHA 256 hashing algorithm, “John” hashed becomes “a8cfcd74832004951b4408cdb0a5dbcd8c7e52d43f7fe- 244bf720582e05241da”.

What is hashing and why we need it? ›

Hashing is the process of using a mathematical function to convert input data into a fixed-length output. Businesses use hashing functions to ensure that the data stored on servers and cloud storage systems remain unreadable even if malicious hackers gain access to the data.

How is hashing different from encryption? ›

Since encryption is two-way, the data can be decrypted so it is readable again. Hashing, on the other hand, is one-way, meaning the plaintext is scrambled into a unique digest, through the use of a salt, that cannot be decrypted.

What is the difference between hashing and indexing? ›

Indexing: With its pre-organized data structures, Indexing offers faster data retrieval, especially for range queries and ordered records. Hashing: Thanks to its direct calculation of data locations, Hashing outperforms Indexing when searching for specific items, especially in large databases.

Top Articles
Digital Transformation Market Size & Share Analysis - Industry Research Report - Growth Trends - 2032
Can F-5 land on aircraft carriers? - Aeroflap
Walgreens Harry Edgemoor
Kathleen Hixson Leaked
Star Sessions Imx
Danatar Gym
Blackstone Launchpad Ucf
Health Benefits of Guava
Google Jobs Denver
Calamity Hallowed Ore
Back to basics: Understanding the carburetor and fixing it yourself - Hagerty Media
Espn Expert Picks Week 2
Craigslist Estate Sales Tucson
Myql Loan Login
Turning the System On or Off
Sports Clips Plant City
The Exorcist: Believer (2023) Showtimes
Kamzz Llc
Christina Steele And Nathaniel Hadley Novel
Rs3 Eldritch Crossbow
Theater X Orange Heights Florida
Reser Funeral Home Obituaries
Elbert County Swap Shop
Hellraiser 3 Parents Guide
Timeline of the September 11 Attacks
1773x / >
Malluvilla In Malayalam Movies Download
13301 South Orange Blossom Trail
101 Lewman Way Jeffersonville In
Ts Modesto
Meowiarty Puzzle
Wells Fargo Bank Florida Locations
Pixel Combat Unblocked
Shnvme Com
Goodwill Houston Select Stores Photos
T&J Agnes Theaters
Police Academy Butler Tech
2008 Chevrolet Corvette for sale - Houston, TX - craigslist
Natashas Bedroom - Slave Commands
Vivek Flowers Chantilly
The TBM 930 Is Another Daher Masterpiece
Author's Purpose And Viewpoint In The Dark Game Part 3
Seminary.churchofjesuschrist.org
Tripadvisor Vancouver Restaurants
Tunica Inmate Roster Release
Thor Majestic 23A Floor Plan
Dwc Qme Database
Shell Gas Stations Prices
Best Conjuration Spell In Skyrim
Embry Riddle Prescott Academic Calendar
Congruent Triangles Coloring Activity Dinosaur Answer Key
Overstock Comenity Login
Latest Posts
Article information

Author: Arline Emard IV

Last Updated:

Views: 6724

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Arline Emard IV

Birthday: 1996-07-10

Address: 8912 Hintz Shore, West Louie, AZ 69363-0747

Phone: +13454700762376

Job: Administration Technician

Hobby: Paintball, Horseback riding, Cycling, Running, Macrame, Playing musical instruments, Soapmaking

Introduction: My name is Arline Emard IV, I am a cheerful, gorgeous, colorful, joyous, excited, super, inquisitive person who loves writing and wants to share my knowledge and understanding with you.