The Wayback Machine - https://web.archive.org/web/20241108100351/https://www.geeksforgeeks.org/load-factor-and-rehashing/
Open In App

Load Factor and Rehashing

Last Updated : 28 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites: Hashing Introduction and Collision handling by separate chaining

How hashing works:

For insertion of a key(K) – value(V) pair into a hash map, 2 steps are required: 
 

  1. K is converted into a small integer (called its hash code) using a hash function.
  2. The hash code is used to find an index (hashCode % arrSize) and the entire linked list at that index(Separate chaining) is first searched for the presence of the K already.
  3. If found, it’s value is updated and if not, the K-V pair is stored as a new node in the list.

Complexity and Load Factor

  • For the first step, the time taken depends on the K and the hash function. 
    For example, if the key is a string “abcd”, then it’s hash function may depend on the length of the string. But for very large values of n, the number of entries into the map, and length of the keys is almost negligible in comparison to n so hash computation can be considered to take place in constant time, i.e, O(1).
  • For the second step, traversal of the list of K-V pairs present at that index needs to be done. For this, the worst case may be that all the n entries are at the same index. So, time complexity would be O(n). But, enough research has been done to make hash functions uniformly distribute the keys in the array so this almost never happens.
  • So, on an average, if there are n entries and b is the size of the array there would be n/b entries on each index. This value n/b is called the load factor that represents the load that is there on our map.
  • This Load Factor needs to be kept low, so that number of entries at one index is less and so is the complexity almost constant, i.e., O(1).

Rehashing:

Rehashing is the process of increasing the size of a hashmap and redistributing the elements to new buckets based on their new hash values. It is done to improve the performance of the hashmap and to prevent collisions caused by a high load factor.

When a hashmap becomes full, the load factor (i.e., the ratio of the number of elements to the number of buckets) increases. As the load factor increases, the number of collisions also increases, which can lead to poor performance. To avoid this, the hashmap can be resized and the elements can be rehashed to new buckets, which decreases the load factor and reduces the number of collisions.

During rehashing, all elements of the hashmap are iterated and their new bucket positions are calculated using the new hash function that corresponds to the new size of the hashmap. This process can be time-consuming but it is necessary to maintain the efficiency of the hashmap.

Why rehashing?
Rehashing is needed in a hashmap to prevent collision and to maintain the efficiency of the data structure.

As elements are inserted into a hashmap, the load factor (i.e., the ratio of the number of elements to the number of buckets) increases. If the load factor exceeds a certain threshold (often set to 0.75), the hashmap becomes inefficient as the number of collisions increases. To avoid this, the hashmap can be resized and the elements can be rehashed to new buckets, which decreases the load factor and reduces the number of collisions. This process is known as rehashing.

Rehashing can be costly in terms of time and space, but it is necessary to maintain the efficiency of the hashmap.

How Rehashing is done?
Rehashing can be done as follows:

  • For each addition of a new entry to the map, check the load factor.
  • If it’s greater than its pre-defined value (or default value of 0.75 if not given), then Rehash.
  • For Rehash, make a new array of double the previous size and make it the new bucketarray.
  • Then traverse to each element in the old bucketArray and call the insert() for each so as to insert it into the new larger bucket array.

Program to implement Rehashing:

C++




#include <iostream>
#include <vector>
#include <functional>
 
class Map {
 
private:
    class MapNode {
    public:
        int key;
        int value;
        MapNode* next;
 
        MapNode(int key, int value) {
            this->key = key;
            this->value = value;
            this->next = NULL;
        }
    };
 
    // The bucket array where
    // the nodes containing K-V pairs are stored
    std::vector<MapNode*> buckets;
 
    // No. of pairs stored - n
    int size;
 
    // Size of the bucketArray - b
    int numBuckets;
 
    // Default loadFactor
    double DEFAULT_LOAD_FACTOR = 0.75;
 
    int getBucketInd(int key) {
        // Using the inbuilt function from the object class
        int hashCode = std::hash<int>()(key);
 
        // array index = hashCode%numBuckets
        return (hashCode % numBuckets);
    }
 
public:
    Map() {
        numBuckets = 5;
 
        buckets.resize(numBuckets);
 
        std::cout << "HashMap created" << std::endl;
        std::cout << "Number of pairs in the Map: " << size << std::endl;
        std::cout << "Size of Map: " << numBuckets << std::endl;
        std::cout << "Default Load Factor : " << DEFAULT_LOAD_FACTOR << std::endl;
    }
 
    void insert(int key, int value) {
        // Getting the index at which it needs to be inserted
        int bucketInd = getBucketInd(key);
 
        // The first node at that index
        MapNode* head = buckets[bucketInd];
 
        // First, loop through all the nodes present at that index
        // to check if the key already exists
        while (head != NULL) {
            // If already present the value is updated
            if (head->key == key) {
                head->value = value;
                return;
            }
            head = head->next;
        }
 
        // new node with the K and V
        MapNode* newElementNode = new MapNode(key, value);
 
        // The head node at the index
        head = buckets[bucketInd];
 
        // the new node is inserted
        // by making it the head
        // and it's next is the previous head
        newElementNode->next = head;
 
        buckets[bucketInd] = newElementNode;
 
        std::cout << "Pair(" << key << ", " << value << ") inserted successfully." << std::endl;
 
        // Incrementing size
        // as new K-V pair is added to the map
        size++;
 
        // Load factor calculated
        double loadFactor = (1 * size) / numBuckets;
 
        std::cout << "Current Load factor = " << loadFactor << std::endl;
 
        // If the load factor is > 0.75, rehashing is done
        if (loadFactor > DEFAULT_LOAD_FACTOR) {
            std::cout << loadFactor << " is greater than " << DEFAULT_LOAD_FACTOR << std::endl;
std::cout << "Therefore Rehashing will be done." << std::endl;
 
        // Rehash
        rehash();
 
        std::cout << "New Size of Map: " << numBuckets << std::endl;
    }
 
    std::cout << "Number of pairs in the Map: " << size << std::endl;
}
 
void rehash() {
    std::cout << "\n***Rehashing Started***\n" << std::endl;
 
    // The present bucket list is made temp
    std::vector<MapNode*> temp = buckets;
 
    // New bucketList of double the old size is created
    buckets.resize(2 * numBuckets);
 
    for (int i = 0; i < 2 * numBuckets; i++) {
        // Initialised to null
        buckets[i] = NULL;
    }
 
    // Now size is made zero
    // and we loop through all the nodes in the original bucket list(temp)
    // and insert it into the new list
    size = 0;
    numBuckets *= 2;
 
    for (int i = 0; i < temp.size(); i++) {
        // head of the chain at that index
        MapNode* head = temp[i];
 
        while (head != NULL) {
            int key = head->key;
            int val = head->value;
 
            // calling the insert function for each node in temp
            // as the new list is now the bucketArray
            insert(key, val);
            head = head->next;
        }
    }
 
    std::cout << "***Rehashing Done***\n" << std::endl;
}
};
 
int main() {
Map map;
// Inserting elements
map.insert(1, 1);
map.insert(2, 2);
map.insert(3, 3);
map.insert(4, 4);
map.insert(5, 5);
map.insert(6, 6);
map.insert(7, 7);
map.insert(8, 8);
map.insert(9, 9);
map.insert(10, 10);
 
return 0;
}


Java




// Java program to implement Rehashing
 
import java.util.ArrayList;
 
class Map<K, V> {
 
    class MapNode<K, V> {
 
        K key;
        V value;
        MapNode<K, V> next;
 
        public MapNode(K key, V value)
        {
            this.key = key;
            this.value = value;
            next = null;
        }
    }
 
    // The bucket array where
    // the nodes containing K-V pairs are stored
    ArrayList<MapNode<K, V> > buckets;
 
    // No. of pairs stored - n
    int size;
 
    // Size of the bucketArray - b
    int numBuckets;
 
    // Default loadFactor
    final double DEFAULT_LOAD_FACTOR = 0.75;
 
    public Map()
    {
        numBuckets = 5;
 
        buckets = new ArrayList<>(numBuckets);
 
        for (int i = 0; i < numBuckets; i++) {
            // Initialising to null
            buckets.add(null);
        }
        System.out.println("HashMap created");
        System.out.println("Number of pairs in the Map: " + size);
        System.out.println("Size of Map: " + numBuckets);
        System.out.println("Default Load Factor : " + DEFAULT_LOAD_FACTOR + "\n");
    }
 
    private int getBucketInd(K key)
    {
 
        // Using the inbuilt function from the object class
        int hashCode = key.hashCode();
 
        // array index = hashCode%numBuckets
        return (hashCode % numBuckets);
    }
 
    public void insert(K key, V value)
    {
        // Getting the index at which it needs to be inserted
        int bucketInd = getBucketInd(key);
 
        // The first node at that index
        MapNode<K, V> head = buckets.get(bucketInd);
 
        // First, loop through all the nodes present at that index
        // to check if the key already exists
        while (head != null) {
 
            // If already present the value is updated
            if (head.key.equals(key)) {
                head.value = value;
                return;
            }
            head = head.next;
        }
 
        // new node with the K and V
        MapNode<K, V> newElementNode = new MapNode<K, V>(key, value);
 
        // The head node at the index
        head = buckets.get(bucketInd);
 
        // the new node is inserted
        // by making it the head
        // and it's next is the previous head
        newElementNode.next = head;
 
        buckets.set(bucketInd, newElementNode);
 
        System.out.println("Pair(" + key + ", " + value + ") inserted successfully.\n");
 
        // Incrementing size
        // as new K-V pair is added to the map
        size++;
 
        // Load factor calculated
        double loadFactor = (1.0 * size) / numBuckets;
 
        System.out.println("Current Load factor = " + loadFactor);
 
        // If the load factor is > 0.75, rehashing is done
        if (loadFactor > DEFAULT_LOAD_FACTOR) {
            System.out.println(loadFactor + " is greater than " + DEFAULT_LOAD_FACTOR);
            System.out.println("Therefore Rehashing will be done.\n");
 
            // Rehash
            rehash();
 
            System.out.println("New Size of Map: " + numBuckets + "\n");
        }
 
        System.out.println("Number of pairs in the Map: " + size);
        System.out.println("Size of Map: " + numBuckets + "\n");
    }
 
    private void rehash()
    {
 
        System.out.println("\n***Rehashing Started***\n");
 
        // The present bucket list is made temp
        ArrayList<MapNode<K, V> > temp = buckets;
 
        // New bucketList of double the old size is created
        buckets = new ArrayList<MapNode<K, V> >(2 * numBuckets);
 
        for (int i = 0; i < 2 * numBuckets; i++) {
            // Initialised to null
            buckets.add(null);
        }
        // Now size is made zero
        // and we loop through all the nodes in the original bucket list(temp)
        // and insert it into the new list
        size = 0;
        numBuckets *= 2;
 
        for (int i = 0; i < temp.size(); i++) {
 
            // head of the chain at that index
            MapNode<K, V> head = temp.get(i);
 
            while (head != null) {
                K key = head.key;
                V val = head.value;
 
                // calling the insert function for each node in temp
                // as the new list is now the bucketArray
                insert(key, val);
                head = head.next;
            }
        }
 
        System.out.println("\n***Rehashing Ended***\n");
    }
 
    public void printMap()
    {
 
        // The present bucket list is made temp
        ArrayList<MapNode<K, V> > temp = buckets;
 
        System.out.println("Current HashMap:");
        // loop through all the nodes and print them
        for (int i = 0; i < temp.size(); i++) {
 
            // head of the chain at that index
            MapNode<K, V> head = temp.get(i);
 
            while (head != null) {
                System.out.println("key = " + head.key + ", val = " + head.value);
 
                head = head.next;
            }
        }
        System.out.println();
    }
   
      //Function to get an element from Map
      public V getValue(K key){
          //Get actual index of the key
        int actualIndex = getBucketInd(key);
        MapNode<K,V> temp = buckets.get(actualIndex);
          //Search for key in list
        while(temp != null){
            if(temp.key == key){
                return temp.value;
            }
            temp = temp.next;
        }
        return null;
    }
}
 
public class GFG {
 
    public static void main(String[] args)
    {
 
        // Creating the Map
        Map<Integer, String> map = new Map<Integer, String>();
 
        // Inserting elements
        map.insert(1, "Geeks");
        map.printMap();
 
        map.insert(2, "forGeeks");
        map.printMap();
 
        map.insert(3, "A");
        map.printMap();
 
        map.insert(4, "Computer");
        map.printMap();
 
        map.insert(5, "Portal");
        map.printMap();
       
      //Get element from Map
      int key = 4;
      String value = map.getValue(key);
      System.out.println("Value at key "+ key +" is: "+ value);
    }
}


Python3




# Python3 program to implement Rehashing
 
class Map:
 
    class MapNode:
        def __init__(self,key,value):
            self.key=key
            self.value=value
            self.next=None
 
    # The bucket array where
    # the nodes containing K-V pairs are stored
    buckets=list()
 
    # No. of pairs stored - n
    size=0
 
    # Size of the bucketArray - b
    numBuckets=0
 
    # Default loadFactor
    DEFAULT_LOAD_FACTOR = 0.75
 
    def __init__(self):
        Map.numBuckets = 5
 
        Map.buckets = [None]*Map.numBuckets
 
        print("HashMap created")
        print("Number of pairs in the Map: " + str(Map.size))
        print("Size of Map: " + str(Map.numBuckets))
        print("Default Load Factor : " + str(Map.DEFAULT_LOAD_FACTOR) + "\n")
 
    def getBucketInd(self,key):
 
        # Using the inbuilt function from the object class
        hashCode = hash(key)
 
        # array index = hashCode%numBuckets
        return (hashCode % Map.numBuckets)
 
    def insert(self,key,value):
 
        # Getting the index at which it needs to be inserted
        bucketInd = self.getBucketInd(key)
 
        # The first node at that index
        head = Map.buckets[bucketInd]
 
        # First, loop through all the nodes present at that index
        # to check if the key already exists
        while (head != None):
 
            # If already present the value is updated
            if (head.key==key):
                head.value = value
                return
            head = head.next
 
        # new node with the K and V
        newElementNode = Map.MapNode(key, value)
 
        # The head node at the index
        head = Map.buckets[bucketInd]
 
        # the new node is inserted
        # by making it the head
        # and it's next is the previous head
        newElementNode.next = head
 
        Map.buckets[bucketInd]= newElementNode
 
        print("Pair(\" {} \", \" {} \") inserted successfully.".format(key,value))
 
        # Incrementing size
        # as new K-V pair is added to the map
        Map.size+=1
 
        # Load factor calculated
        loadFactor = (1* Map.size) / Map.numBuckets
 
        print("Current Load factor = " + str(loadFactor))
 
        # If the load factor is > 0.75, rehashing is done
        if (loadFactor > Map.DEFAULT_LOAD_FACTOR):
            print(str(loadFactor) + " is greater than " + str(Map.DEFAULT_LOAD_FACTOR))
            print("Therefore Rehashing will be done.")
 
            # Rehash
            self.rehash()
 
            print("New Size of Map: " + str(Map.numBuckets))
 
        print("Number of pairs in the Map: " + str(Map.size))
        print("Size of Map: " + str(Map.numBuckets))
 
    def rehash(self):
 
        print("\n***Rehashing Started***\n")
 
        # The present bucket list is made temp
        temp = Map.buckets
 
        # New bucketList of double the old size is created
        buckets =(2 * Map.numBuckets)
 
        for i in range(2 * Map.numBuckets):
            # Initialised to null
            Map.buckets.append(None)
 
        # Now size is made zero
        # and we loop through all the nodes in the original bucket list(temp)
        # and insert it into the new list
        Map.size = 0
        Map.numBuckets *= 2
 
        for i in range(len(temp)):
 
            # head of the chain at that index
            head = temp[i]
 
            while (head != None):
                key = head.key
                val = head.value
 
                # calling the insert function for each node in temp
                # as the new list is now the bucketArray
                self.insert(key, val)
                head = head.next
 
        print("\n***Rehashing Ended***")
 
    def printMap(self):
 
        # The present bucket list is made temp
        temp = Map.buckets
 
        print("Current HashMap:")
        # loop through all the nodes and print them
        for i in range(len(temp)):
 
            # head of the chain at that index
            head = temp[i]
 
            while (head != None):
                print("key = \" {} \", val = {}" .format(head.key,head.value))
 
                head = head.next
        print()
 
 
if __name__ == '__main__':
    # Creating the Map
    map = Map()
 
    # Inserting elements
    map.insert(1, "Geeks")
    map.printMap()
 
    map.insert(2, "forGeeks")
    map.printMap()
 
    map.insert(3, "A")
    map.printMap()
 
    map.insert(4, "Computer")
    map.printMap()
 
    map.insert(5, "Portal")
    map.printMap()
 
# This code is contributed by Amartya Ghosh


C#




using System;
using System.Collections.Generic;
 
public class Map {
    private class MapNode {
        public int key;
        public int value;
        public MapNode next;
        public MapNode(int key, int value)
        {
            this.key = key;
            this.value = value;
            this.next = null;
        }
    }
 
    private List<MapNode> buckets;
    private int size;
    private int numBuckets;
    private double DEFAULT_LOAD_FACTOR = 0.75;
 
    public Map()
    {
        numBuckets = 5;
        buckets = new List<MapNode>(numBuckets);
        for (int i = 0; i < numBuckets; i++) {
            buckets.Add(null);
        }
    }
 
    private int getBucketInd(int key)
    {
        int hashCode = key.GetHashCode();
        return (hashCode % numBuckets);
    }
 
    public void insert(int key, int value)
    {
        int bucketInd = getBucketInd(key);
        MapNode head = buckets[bucketInd];
        while (head != null) {
            if (head.key == key) {
                head.value = value;
                return;
            }
            head = head.next;
        }
        MapNode newElementNode = new MapNode(key, value);
 
        head = buckets[bucketInd];
        newElementNode.next = head;
 
        buckets[bucketInd] = newElementNode;
        size++;
        double loadFactor = (1.0 * size) / numBuckets;
 
        if (loadFactor > DEFAULT_LOAD_FACTOR) {
            Console.WriteLine(loadFactor
                              + " is greater than "
                              + DEFAULT_LOAD_FACTOR);
            Console.WriteLine(
                "Therefore Rehashing will be done.");
 
            rehash();
 
            Console.WriteLine("New Size of Map: "
                              + numBuckets);
        }
 
        Console.WriteLine("Number of pairs in the Map: "
                          + size);
    }
 
    private void rehash()
    {
        Console.WriteLine("\n***Rehashing Started***\n");
 
        // The present bucket list is made temp
        List<MapNode> temp = buckets;
 
        // New bucketList of double the old size is created
        numBuckets *= 2;
        buckets = new List<MapNode>(numBuckets);
        for (int i = 0; i < numBuckets; i++) {
            buckets.Add(null);
        }
 
        // Now size is made zero
        // and we loop through all the nodes in the original
        // bucket list(temp) and insert it into the new list
        size = 0;
 
        for (int i = 0; i < temp.Count; i++) {
            // head of the chain at that index
            MapNode head = temp[i];
 
            while (head != null) {
                int key = head.key;
                int val = head.value;
 
                // calling the insert function for each node
                // in temp as the new list is now the
                // bucketArray
                insert(key, val);
                head = head.next;
            }
        }
 
        Console.WriteLine("***Rehashing Done***\n");
    }
}
 
class Program {
    static void Main(string[] args)
    {
        Map map = new Map();
        // Inserting elements
        map.insert(1, 1);
        map.insert(2, 2);
        map.insert(3, 3);
        map.insert(4, 4);
        map.insert(5, 5);
        map.insert(6, 6);
        map.insert(7, 7);
        map.insert(8, 8);
        map.insert(9, 9);
        map.insert(10, 10);
    }
}
 
//This Code is Contributed by NarasingaNikhil


Javascript




// javascript program to implement Rehashing
class Map {
    constructor() {
        //  The bucket array where
    // the nodes containing K-V pairs are stored
        this.buckets = [];
        this.numBuckets = 5;
        // No. of pairs stored - n
        this.size = 0;
        // Default loadFactor
        this.DEFAULT_LOAD_FACTOR = 0.75;
 
        for (let i = 0; i < this.numBuckets; i++) {
            this.buckets.push(null);
        }
    }
 
    getBucketInd(key) {
        //Using the inbuilt function from the object class
        let hashCode = key.toString().hashCode();
       // array index = hashCode%numBuckets
        return (hashCode % this.numBuckets);
    }
 
    insert(key, value) {
         //Getting the index at which it needs to be inserted
        let bucketInd = this.getBucketInd(key);
        
       // The first node at that index
        let head = this.buckets[bucketInd];
        // First, loop through all the nodes present at that index
        // to check if the key already exists
        while (head) {
            //If already present the value is updated
            if (head.key == key) {
                head.value = value;
                return;
            }
            head = head.next;
        }
//new node with the K and V
        let newElementNode = new MapNode(key, value);
        //The head node at the index
        head = this.buckets[bucketInd];
        // the new node is inserted
        // by making it the head
        // and it's next is the previous head
        newElementNode.next = head;
        this.buckets[bucketInd] = newElementNode;
        this.size++;
        let loadFactor = (1.0 * this.size) / this.numBuckets;
 
        if (loadFactor > this.DEFAULT_LOAD_FACTOR) {
            console.log(loadFactor
                        + " is greater than "
                        + this.DEFAULT_LOAD_FACTOR);
                        //If the load factor is > 0.75, rehashing is done
            console.log(
                "Therefore Rehashing will be done.");
//Rehash
            this.rehash();
 
            console.log("New Size of Map: "
                        + this.numBuckets);
        }
 
        console.log("Number of pairs in the Map: "
                    + this.size);
    }
 
    rehash() {
        console.log("\n***Rehashing Started***\n");
//he present bucket list is made temp
        let temp = this.buckets;
        // New bucketList of double the old size is created
        this.numBuckets *= 2;
        //Initialised to null
        this.buckets = [];
        for (let i = 0; i < this.numBuckets; i++) {
            this.buckets.push(null);
        }
 //Now size is made zero
        // and we loop through all the nodes in the original bucket list(temp)
        // and insert it into the new list
        this.size = 0;
 
        for (let i = 0; i < temp.length; i++) {
            let head = temp[i];
 
            while (head) {
                let key = head.key;
                let val = head.value;
//calling the insert function for each node in temp
                // as the new list is now the bucketArray
                this.insert(key, val);
                head = head.next;
            }
        }
 
        console.log("***Rehashing Done***\n");
    }
 
}
 
class MapNode {
    constructor(key, value) {
        this.key = key;
        this.value = value;
        this.next = null;
    }
}
 
String.prototype.hashCode = function () {
    let hash = 0;
    if (this.length == 0) {
        return hash;
    }
    for (let i = 0; i < this.length; i++) {
        let char = this.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}
 
 
let map = new Map();
// Inserting elements
map.insert(1, 1);
map.insert(2, 2);
map.insert(3, 3);
map.insert(4, 4);
map.insert(5, 5);
map.insert(6, 6);
map.insert(7, 7);
map.insert(8, 8);
map.insert(9, 9);
map.insert(10, 10);
 
//Code is contributed by NarasingaNikhil


Output: 

HashMap created
Number of pairs in the Map: 0
Size of Map: 5
Default Load Factor : 0.75

Pair(1, Geeks) inserted successfully.

Current Load factor = 0.2
Number of pairs in the Map: 1
Size of Map: 5

Current HashMap:
key = 1, val = Geeks

Pair(2, forGeeks) inserted successfully.

Current Load factor = 0.4
Number of pairs in the Map: 2
Size of Map: 5

Current HashMap:
key = 1, val = Geeks
key = 2, val = forGeeks

Pair(3, A) inserted successfully.

Current Load factor = 0.6
Number of pairs in the Map: 3
Size of Map: 5

Current HashMap:
key = 1, val = Geeks
key = 2, val = forGeeks
key = 3, val = A

Pair(4, Computer) inserted successfully.

Current Load factor = 0.8
0.8 is greater than 0.75
Therefore Rehashing will be done.


***Rehashing Started***

Pair(1, Geeks) inserted successfully.

Current Load factor = 0.1
Number of pairs in the Map: 1
Size of Map: 10

Pair(2, forGeeks) inserted successfully.

Current Load factor = 0.2
Number of pairs in the Map: 2
Size of Map: 10

Pair(3, A) inserted successfully.

Current Load factor = 0.3
Number of pairs in the Map: 3
Size of Map: 10

Pair(4, Computer) inserted successfully.

Current Load factor = 0.4
Number of pairs in the Map: 4
Size of Map: 10


***Rehashing Ended***

New Size of Map: 10

Number of pairs in the Map: 4
Size of Map: 10

Current HashMap:
key = 1, val = Geeks
key = 2, val = forGeeks
key = 3, val = A
key = 4, val = Computer

Pair(5, Portal) inserted successfully.

Current Load factor = 0.5
Number of pairs in the Map: 5
Size of Map: 10

Current HashMap:
key = 1, val = Geeks
key = 2, val = forGeeks
key = 3, val = A
key = 4, val = Computer
key = 5, val = Portal

 

The time complexity of the insert operation is O(1) and the 
Auxiliary space :  O(n). 

The time complexity of the rehash operation is O(n) and the 
Auxiliary space: O(n).



Previous Article
Next Article

Similar Reads

Find sum of a number and its maximum prime factor
Given an integer N, the task is to find the sum of N and it's maximum prime factor.Examples: Input: 19 Output: 38 Maximum prime factor of 19 is 19. Hence, 19 + 19 = 38Input: 8 Output: 10 8 + 2 = 10 Approach: Find the largest prime factor of the number and store it in maxPrimeFact then print the value of N + maxPrimeFact.Below is the implementation
6 min read
Sum of Maximum and Minimum prime factor of every number in the Array
Given an array arr[], the task is to find the sum of the maximum and the minimum prime factor of every number in the given array.Examples: Input: arr[] = {15} Output: 8 The maximum and the minimum prime factors of 15 are 5 and 3 respectively.Input: arr[] = {5, 10, 15, 20, 25, 30} Output: 10 7 8 7 10 7 Approach: The idea is to use Sieve of Eratosthe
9 min read
Sum of largest prime factor of each number less than equal to n
Given a non-negative integer n. The problem is to find the sum of the largest prime factor of each number less than equal to n. Examples: Input : n = 10 Output : 32 Largest prime factor of each number Prime factor of 2 = 2 Prime factor of 3 = 3 Prime factor of 4 = 2 Prime factor of 5 = 5 Prime factor of 6 = 3 Prime factor of 7 = 7 Prime factor of 8
8 min read
N-th prime factor of a given number
Given Q queries which consist of two integers, one is number(1 <= number <= 106) and the other is N., the task is to find the N-th prime factor of the given number. Examples: Input: Number of Queries, Q = 4 number = 6, N = 1 number = 210, N = 3 number = 210, N = 2 number = 60, N = 2Output: 2 5 3 2 Explanations: For number = 6, The prime facto
15 min read
Numbers with sum of digits equal to the sum of digits of its all prime factor
Given a range, the task is to find the count of the numbers in the given range such that the sum of its digit is equal to the sum of all its prime factors digits sum.Examples: Input: l = 2, r = 10 Output: 5 2, 3, 4, 5 and 7 are such numbers Input: l = 15, r = 22 Output: 3 17, 19 and 22 are such numbers As, 17 and 19 are already prime. Prime Factors
13 min read
Count all the numbers less than 10^6 whose minimum prime factor is N
Given a number N which is prime. The task is to find all the numbers less than or equal to 10^6 whose minimum prime factor is N.Examples: Input: N = 2 Output: 500000 Input: N = 3 Output: 166667 Approach: Use sieve of Eratosthenes to find the solution to the problem. Store all the prime numbers less than 10^6 . Form another sieve that will store the
7 min read
Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
Given two strings, the task is to check whether the frequencies of a character(for each character) in one string are multiple or a factor in another string. If it is, then output "YES", otherwise output "NO". Examples: Input: s1 = "aabccd", s2 = "bbbaaaacc" Output: YES Frequency of 'a' in s1 and s2 are 2 and 4 respectively, and 2 is a factor of 4 F
6 min read
Most frequent factor in a range of integers
You are given a range of numbers, from lower number to higher number (both inclusive). Consider all the factors of these numbers except 1, the task is to find the factor which appears the maximum number of times. If more than one number have maximum frequency then print anyone of them.Examples: Input : lower=10 higher=14 Output : The factor with ma
4 min read
Maximum length subsequence such that adjacent elements in the subsequence have a common factor
Given an array arr[], the task is to find the maximum length of a subsequence such that the adjacent elements in the subsequence have a common factor. Examples: Input: arr[] = { 13, 2, 8, 6, 3, 1, 9 } Output: 5Max length subsequence with satisfied conditions: { 2, 8, 6, 3, 9 } Input: arr[] = { 12, 2, 8, 6, 3, 1, 9 } Output: 6Max length subsequence
9 min read
Count the nodes of the given tree whose weight has X as a factor
Given a tree, and the weights of all the nodes, the task is to count the nodes whose weights are divisible by x.Examples: Input: x = 5 Output: 2 Only the nodes 1 and 2 have weights divisible by 5. Approach: Perform dfs on the tree and for every node, check if it's weight is divisible by x or not. If yes then increment the count.Implementation: C/C+
4 min read
Find the total number of composite factor for a given number
Given an integer N, the task is to find the total number of composite factors of N. Composite factors of a number are the factors which are not prime.Examples: Input: N = 24 Output: 5 1, 2, 3, 4, 6, 8, 12 and 24 are the factors of 24. Out of which only 4, 6, 8, 12 and 24 are composites.Input: N = 100 Output: 6 Approach: Find all the factors of N an
6 min read
Count minimum factor jumps required to reach the end of an Array
Given an array of positive integers arr[], the task is to count the minimum factor jumps required to reach the end of an array. From any particular index i, the jump can be made only for K indices where K is a factor of arr[i]. Examples: Input: arr[] = {2, 8, 16, 55, 99, 100} Output: 2 Explanation: The optimal jumps are: a) Start from 2. b) Since f
15+ min read
Count of pairs (i, j) in the array such that arr[i] is a factor of arr[j]
Given an array of integers arr, the task is to calculate the number of pairs (i, j) where i < j such that arr[j] % arr[i] = 0.Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 5Input: arr[] = {1, 1, 2, 2, 3, 3} Output: 11 Approach 1: Iterate over all pairs of the array and keep incrementing the count of pairs that satisfy the required condition.
10 min read
Find largest factor of N such that N/F is less than K
Given two numbers N and K, the task is to find the minimum value X such that N < X*K. Examples: Input: N = 8, K = 7 Output: 2 Explanation: Numbers less than K divisible by N are 1, 2 and 4. So the minimum value of X is 2 such that 8 < 2*7 = 14.Input: N = 999999733, K = 999999732 Output: 999999733 Explanation: Since 999999733 is a prime number
10 min read
Greatest odd factor of an even number
Given an even number N, the task is to find the greatest possible odd factor of N. Examples: Input: N = 8642 Output: 4321 Explanation: Here, factors of 8642 are {1, 8642, 2, 4321, 29, 298, 58, 149} in which odd factors are {1, 4321, 29, 149} and the greatest odd factor among all odd factors is 4321. Input: N = 100 Output: 25 Explanation: Here, fact
4 min read
Count of distinct power of prime factor of N
Given a positive integer N, the task is to find the total number of distinct power of prime factor of the given number N.Examples: Input: N = 216 Output: 4 Explanation: 216 can be expressed as 2 * 22 * 3 * 32. The factors satisfying the conditions are 2, 22, 3 and 32 as all of them are written as distinct positive powers of prime factors.Input: N =
6 min read
Longest subarray in which all elements are a factor of K
Given an array A[] of size N and a positive integer K, the task is to find the length of the longest subarray such that all elements of the subarray is a factor of K. Examples: Input: A[] = {2, 8, 3, 10, 6, 7, 4, 9}, K = 60Output: 3Explanation: The longest subarray in which all elements are a factor of K (= 60) is {3, 10, 6}. Therefore, the require
6 min read
Count subsets consisting of each element as a factor of the next element in that subset
Given an array arr[] of size N, the task is to find the number of non-empty subsets present in the array such that every element( except the last) in the subset is a factor of the next adjacent element present in that subset. The elements in a subset can be rearranged, therefore, if any rearrangement of a subset satisfies the condition, then that s
15+ min read
Minimize steps required to make two values equal by repeated division by any of their prime factor which is less than M
Given three positive integers M, X, and Y, the task is to find the minimum number of operations required to make X and Y equal such that in each operation divide X or Y by one of its prime factor less than M. If it is not possible to make X and Y equal, then print "-1". Examples: Input: X = 20, Y =16, M = 10Output: 3Explanation:Perform the operatio
11 min read
Count of numbers up to N having at least one prime factor common with N
Given an integer N, the task is to count the number of integers from the range [1, N] having at least one in common prime factor with N other than 1. Examples: Input: N = 5Output: 1Explanation: Since 5 is prime. Therefore, there is no other number which is at most N, that has at least one common factor with N except N itself. Therefore, the count i
10 min read
Convert a number to another by dividing by its factor or removing first occurrence of a digit from an array
Given two positive integers A, B, and an array D[] consisting only of digits [0-9], the task is to check if it is possible to reduce A to B by repeatedly dividing by any of its factors which is present the array D[] or by removing the first occurrence of any of its digit which is present in the array D[]. Examples: Input: A = 5643, B = 81, D[] = {3
14 min read
Kth largest factor of number N
Given two positive integers N and K, the task is to print the Kth largest factor of N. Input: N = 12, K = 3Output: 4Explanation: The factors of 12 are {1, 2, 3, 4, 6, 12}. The largest factor is 12 and the 3rd largest factor is 4. Input: N = 30, K = 2Output: 15Explanation: The factors of 30 are {1, 2, 3, 5, 6, 10, 15, 30} and the 2nd largest factor
12 min read
Height of Factor Tree for a given number
Given a positive integer N, the task is to find the height of the Factor Tree of the given integer N. Examples: Input: N = 20Output: 3Explanation: The height of the Factor Tree of 20 shown in the image below is 3. Input: N = 48Output: 5 Approach: The given problem can be solved by using the steps discussed below: Initialize a variable, say height a
5 min read
Maximum size of subset such that product of all subset elements is a factor of N
Given an integer N and an array arr[] having M integers, the task is to find the maximum size of the subset such that the product of all elements of the subset is a factor of N. Examples: Input: N = 12, arr[] = {2, 3, 4}Output: 2Explanation: The given array 5 subsets such that the product of all elements of the subset is a factor of 12. They are {2
6 min read
Largest integer upto N having greatest prime factor greater than its square root
Given a positive integer N, the task is to find the largest number in the range [1, N] such that the square root of the number is less than its greatest prime factor. Input: N = 15Output: 15Explanation: The prime factors of 15 are {3, 5}. The square root of 15 is 3.87 (i.e, 3.87 < 5). Therefore 15 is the largest valid integer in the given range.
7 min read
Find elements in given Array that are a factor of sum of remaining elements
Given an array A[] of size N, the task is to find the elements in the array which are factors of the sum of the remaining element. So just select an element from an array and take the sum of the remaining elements and check whether the sum is perfectly divisible by the selected element or not. If it is divisible then return the element. Examples: I
11 min read
Smallest integer having at least K prime divisors with difference between each factor at least D
Given two integers D and K. The task is to find the smallest number N which has at least K prime divisors and the difference between each pair of divisors is at least D. Examples Input: D = 3, K = 2Output: 55Explanation: It is smallest number which has 4 divisors 1 and 2 prime divisors 5, 11 and their difference between any of the pair is D. Input:
7 min read
Find sum of values of N at each step after repeatedly dividing it with its smallest factor
Given an integer N, the task is to find the sum of all values of N after repeatedly dividing it with its smallest factor. Examples: Input: N = 5Output: 6Explanation: Initially N = 5. The smallest factor of N is 5 itself. Therefore, the value of N will become N/5 = 5/5 = 1. Hence, the sum of all values of N is 5 + 1 = 6. Input: N = 10.Output: 16Expl
5 min read
Make two numbers equal in at most K steps dividing by their factor
Given integers X, Y, and K, the task is to make X and Y equal in not more than K operations by applying the following operations: Choose an integer A and make X = X/A, (where A is an integer that is greater than 1 and not equal to X).Choose an integer A and make Y = Y/A, (where A is an integer that is greater than 1 and not equal to Y). Examples: I
6 min read
Largest factor of a given number which is a perfect square
Given a number [Tex]N [/Tex]. The task is to find the largest factor of that number which is a perfect square.Examples: Input : N = 420Output : 4Input : N = 100Output : 100A Simple Solution is to traverse all of the numbers in decreasing order from the given number down till 1 and if any of these numbers is a factor of the given number and is also
10 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg