Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Python Naming Conventions
Next article icon

Double Hashing in Python

Last Updated : 21 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Double hashing is a collision resolution technique used in hash tables. It works by using two hash functions to compute two different hash values for a given key. The first hash function is used to compute the initial hash value, and the second hash function is used to compute the step size for the probing sequence. In this article, we'll explore what double hashing actually is and its implementation using Python.

What is Double Hashing?

Double hashing is a collision resolution technique that involves using two hash functions to calculate the index where a data item should be placed in a hash table. When a collision occurs (i.e., when two items map to the same index), the second hash function is applied iteratively until an empty slot is found. This process ensures that items are distributed more evenly throughout the hash table, reducing the likelihood of collisions and improving overall performance.

Implementation in Python:

Below is the implementation of Double Hashing in Python:

Python
from typing import List import math  MAX_SIZE = 10000001   class DoubleHash:     def __init__(self, n: int):         self.TABLE_SIZE = n         self.PRIME = self.__get_largest_prime(n - 1)         self.keysPresent = 0         self.hashTable = [-1] * n      def __get_largest_prime(self, limit: int) -> int:         is_prime = [True] * (limit + 1)         is_prime[0], is_prime[1] = False, False         for i in range(2, int(math.sqrt(limit)) + 1):             if is_prime[i]:                 for j in range(i * i, limit + 1, i):                     is_prime[j] = False         for i in range(limit, -1, -1):             if is_prime[i]:                 return i      def __hash1(self, value: int) -> int:         return value % self.TABLE_SIZE      def __hash2(self, value: int) -> int:         return self.PRIME - (value % self.PRIME)      def is_full(self) -> bool:         return self.TABLE_SIZE == self.keysPresent      def insert(self, value: int) -> None:         if value == -1 or value == -2:             print("ERROR : -1 and -2 can't be inserted in the table")             return         if self.is_full():             print("ERROR : Hash Table Full")             return         probe, offset = self.__hash1(value), self.__hash2(value)         while self.hashTable[probe] != -1:             if -2 == self.hashTable[probe]:                 break             probe = (probe + offset) % self.TABLE_SIZE         self.hashTable[probe] = value         self.keysPresent += 1      def erase(self, value: int) -> None:         if not self.search(value):             return         probe, offset = self.__hash1(value), self.__hash2(value)         while self.hashTable[probe] != -1:             if self.hashTable[probe] == value:                 self.hashTable[probe] = -2                 self.keysPresent -= 1                 return             else:                 probe = (probe + offset) % self.TABLE_SIZE      def search(self, value: int) -> bool:         probe, offset, initialPos, firstItr = self.__hash1(             value), self.__hash2(value), self.__hash1(value), True         while True:             if self.hashTable[probe] == -1:                 break             elif self.hashTable[probe] == value:                 return True             elif probe == initialPos and not firstItr:                 return False             else:                 probe = (probe + offset) % self.TABLE_SIZE             firstItr = False         return False      def print(self) -> None:         print(*self.hashTable, sep=', ')   if __name__ == '__main__':     myHash = DoubleHash(13)      # Inserts random element in the hash table     insertions = [115, 12, 87, 66, 123]     for insertion in insertions:         myHash.insert(insertion)     print("Status of hash table after initial insertions : ", end="")     myHash.print()      # Searches for random element in the hash table, and prints them if found.     queries = [1, 12, 2, 3, 69, 88, 115]     n2 = len(queries)     print("\nSearch operation after insertion : ")      for i in range(n2):         if myHash.search(queries[i]):             print(queries[i], "present")      # Deletes random element from the hash table.     deletions = [123, 87, 66]     n3 = len(deletions)      for i in range(n3):         myHash.erase(deletions[i])      print("Status of hash table after deleting elements : ", end='')     myHash.print() 

Output
Status of hash table after initial insertions : -1, 66, -1, -1, -1, -1, 123, -1, -1, 87, -1, 115, 12  Search operation after insertion :  12 present 115 present Status of hash table after deleting ele...

Benefits of Double Hashing:

  • Reduced Collisions: Double hashing distributes items more evenly throughout the hash table, reducing the likelihood of collisions.
  • Improved Performance: By resolving collisions efficiently, double hashing ensures faster data retrieval and manipulation.
  • Simplicity: Double hashing is relatively easy to implement and understand compared to other collision resolution techniques like chaining or open addressing

By distributing items more evenly than techniques such as linear probing, double hashing can improve the performance of hash tables significantly and reduce collisions as well. In Python, the implementation of double hashing is plain and simple and can make a big difference in scenarios where efficient data storage and retrieval are essential. By learning and using double hashing, programmers can build more substantial and extensive applications.


Next Article
Python Naming Conventions

D

dahiyasourabh444
Improve
Article Tags :
  • Hash
  • DSA
  • Python-DSA
Practice Tags :
  • Hash

Similar Reads

  • Expressions in Python
    An expression is a combination of operators and operands that is interpreted to produce some other value. In any programming language, an expression is evaluated as per the precedence of its operators. So that if there is more than one operator in an expression, their precedence decides which operat
    5 min read
  • Appending to 2D List in Python
    A 2D list in Python is a list of lists where each sublist can hold elements. Appending to a 2D list involves adding either a new sublist or elements to an existing sublist. The simplest way to append a new sublist to a 2D list is by using the append() method. [GFGTABS] Python a = [[1, 2], [3, 4]] #
    2 min read
  • Python input() Function
    Python input() function is used to take user input. By default, it returns the user input in form of a string. input() Function Syntax:  input(prompt)prompt [optional]: any string value to display as input message Ex: input("What is your name? ") Returns: Return a string value as input by the user.
    4 min read
  • Multiline Comments in Python
    A multiline comment in Python is a comment that spans multiple lines, used to provide detailed explanations, disable large sections of code, or improve code readability. Python does not have a dedicated syntax for multiline comments, but developers typically use one of the following approaches: It h
    4 min read
  • Python Naming Conventions
    Python, known for its simplicity and readability, places a strong emphasis on writing clean and maintainable code. One of the key aspects contributing to this readability is adhering to Python Naming Conventions. In this article, we'll delve into the specifics of Python Naming Conventions, covering
    4 min read
  • Python Functions
    Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
    11 min read
  • API Changes For 3.8.0 in Python
    In this article, we will explore the changes in the API after the launch of Python 3.8.0. Python, a dynamic and widely-used programming language, continuously evolves with new releases, introducing enhancements and changes to improve developer productivity and code quality. Python 3.8.0, released in
    6 min read
  • Taking input from console in Python
    What is Console in Python? Console (also called Shell) is basically a command line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error free then it runs the command and gives required output otherwise shows the error message. A Python Console looks
    2 min read
  • Matrix manipulation in Python
    In python matrix can be implemented as 2D list or 2D Array. Forming matrix from latter, gives the additional functionalities for performing various operations in matrix. These operations and array are defines in module "numpy". Operation on Matrix : 1. add() :- This function is used to perform eleme
    4 min read
  • Define and Call Methods in a Python Class
    In object-oriented programming, a class is a blueprint for creating objects, and methods are functions associated with those objects. Methods in a class allow you to define behavior and functionality for the objects created from that class. Python, being an object-oriented programming language, prov
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences