Load Factor and Rehashing
Last Updated :
11 Jul, 2025
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:
- K is converted into a small integer (called its hash code) using a hash function.
- 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.
- 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).
Similar Reads
Hashing in Data Structure Hashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Introduction to Hashing Hashing refers to the process of generating a small sized output (that can be used as index in a table) from an input of typically large and variable size. Hashing uses mathematical formulas known as hash functions to do the transformation. This technique determines an index or location for the stor
7 min read
What is Hashing? Hashing refers to the process of generating a fixed-size output from an input of variable size using the mathematical formulas known as hash functions. This technique determines an index or location for the storage of an item in a data structure. Need for Hash data structureThe amount of data on the
3 min read
Index Mapping (or Trivial Hashing) with negatives allowed Index Mapping (also known as Trivial Hashing) is a simple form of hashing where the data is directly mapped to an index in a hash table. The hash function used in this method is typically the identity function, which maps the input data to itself. In this case, the key of the data is used as the ind
7 min read
Separate Chaining Collision Handling Technique in Hashing Separate Chaining is a collision handling technique. Separate chaining is one of the most popular and commonly used techniques in order to handle collisions. In this article, we will discuss about what is Separate Chain collision handling technique, its advantages, disadvantages, etc.There are mainl
3 min read
Open Addressing Collision Handling technique in Hashing Open Addressing is a method for handling collisions. In Open Addressing, all elements are stored in the hash table itself. So at any point, the size of the table must be greater than or equal to the total number of keys (Note that we can increase table size by copying old data if needed). This appro
7 min read
Double Hashing 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
15+ min read
Load Factor and Rehashing 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: K is converted into a small integer (called its hash code) using a hash function.The hash code is used to find an index
15+ min read
Easy problems on Hashing
Check if an array is subset of another arrayGiven two arrays a[] and b[] of size m and n respectively, the task is to determine whether b[] is a subset of a[]. Both arrays are not sorted, and elements are distinct.Examples: Input: a[] = [11, 1, 13, 21, 3, 7], b[] = [11, 3, 7, 1] Output: trueInput: a[]= [1, 2, 3, 4, 5, 6], b = [1, 2, 4] Output
13 min read
Union and Intersection of two Linked List using HashingGiven two singly Linked Lists, create union and intersection lists that contain the union and intersection of the elements present in the given lists. Each of the two linked lists contains distinct node values.Note: The order of elements in output lists doesnât matter. Examples:Input:head1 : 10 -
10 min read
Two Sum - Pair with given SumGiven an array arr[] of n integers and a target value, check if there exists a pair whose sum equals the target. This is a variation of the 2Sum problem.Examples: Input: arr[] = [0, -1, 2, -3, 1], target = -2Output: trueExplanation: There is a pair (1, -3) with the sum equal to given target, 1 + (-3
15+ min read
Max Distance Between Two OccurrencesGiven an array arr[], the task is to find the maximum distance between two occurrences of any element. If no element occurs twice, return 0.Examples: Input: arr = [1, 1, 2, 2, 2, 1]Output: 5Explanation: distance for 1 is: 5-0 = 5, distance for 2 is: 4-2 = 2, So max distance is 5.Input : arr[] = [3,
8 min read
Most frequent element in an arrayGiven an integer array arr[], find the element that appears most frequently. If multiple elements have the same highest frequency, return the largest among them.Examples: Input : arr[] = [1, 3, 2, 1, 4, 1]Output : 1Explanation: 1 appears three times in array which is maximum frequency.Input : arr[]
10 min read
Only Repeating From 1 To n-1Given an array arr[] of size n filled with numbers from 1 to n-1 in random order. The array has only one repetitive element. The task is to find the repetitive element.Examples:Input: arr[] = [1, 3, 2, 3, 4]Output: 3Explanation: The number 3 is the only repeating element.Input: arr[] = [1, 5, 1, 2,
15+ min read
Check for Disjoint Arrays or SetsGiven two arrays a and b, check if they are disjoint, i.e., there is no element common between both the arrays.Examples: Input: a[] = {12, 34, 11, 9, 3}, b[] = {2, 1, 3, 5} Output: FalseExplanation: 3 is common in both the arrays.Input: a[] = {12, 34, 11, 9, 3}, b[] = {7, 2, 1, 5} Output: True Expla
11 min read
Non-overlapping sum of two setsGiven two arrays A[] and B[] of size n. It is given that both array individually contains distinct elements. We need to find the sum of all elements that are not common.Examples: Input : A[] = {1, 5, 3, 8} B[] = {5, 4, 6, 7}Output : 291 + 3 + 4 + 6 + 7 + 8 = 29Input : A[] = {1, 5, 3, 8} B[] = {5, 1,
9 min read
Check if two arrays are equal or notGiven two arrays, a and b of equal length. The task is to determine if the given arrays are equal or not. Two arrays are considered equal if:Both arrays contain the same set of elements.The arrangements (or permutations) of elements may be different.If there are repeated elements, the counts of each
6 min read
Find missing elements of a rangeGiven an array, arr[0..n-1] of distinct elements and a range [low, high], find all numbers that are in a range, but not the array. The missing elements should be printed in sorted order.Examples: Input: arr[] = {10, 12, 11, 15}, low = 10, high = 15Output: 13, 14Input: arr[] = {1, 14, 11, 51, 15}, lo
15+ min read
Minimum Subsets with Distinct ElementsYou are given an array of n-element. You have to make subsets from the array such that no subset contain duplicate elements. Find out minimum number of subset possible.Examples : Input : arr[] = {1, 2, 3, 4}Output :1Explanation : A single subset can contains all values and all values are distinct.In
9 min read
Remove minimum elements such that no common elements exist in two arraysGiven two arrays arr1[] and arr2[] consisting of n and m elements respectively. The task is to find the minimum number of elements to remove from each array such that intersection of both arrays becomes empty and both arrays become mutually exclusive.Examples: Input: arr[] = { 1, 2, 3, 4}, arr2[] =
8 min read
2 Sum - Count pairs with given sumGiven an array arr[] of n integers and a target value, the task is to find the number of pairs of integers in the array whose sum is equal to target.Examples: Input: arr[] = {1, 5, 7, -1, 5}, target = 6Output: 3Explanation: Pairs with sum 6 are (1, 5), (7, -1) & (1, 5). Input: arr[] = {1, 1, 1,
9 min read
Count quadruples from four sorted arrays whose sum is equal to a given value xGiven four sorted arrays each of size n of distinct elements. Given a value x. The problem is to count all quadruples(group of four numbers) from all the four arrays whose sum is equal to x.Note: The quadruple has an element from each of the four arrays. Examples: Input : arr1 = {1, 4, 5, 6}, arr2 =
15+ min read
Sort elements by frequency | Set 4 (Efficient approach using hash)Print the elements of an array in the decreasing frequency if 2 numbers have the same frequency then print the one which came first. Examples: Input : arr[] = {2, 5, 2, 8, 5, 6, 8, 8} Output : arr[] = {8, 8, 8, 2, 2, 5, 5, 6} Input : arr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8} Output : arr[] = {8,
12 min read
Find all pairs (a, b) in an array such that a % b = kGiven an array with distinct elements, the task is to find the pairs in the array such that a % b = k, where k is a given integer. You may assume that a and b are in small range Examples : Input : arr[] = {2, 3, 5, 4, 7} k = 3Output : (7, 4), (3, 4), (3, 5), (3, 7)7 % 4 = 33 % 4 = 33 % 5 = 33 % 7 =
15 min read
Group words with same set of charactersGiven a list of words with lower cases. Implement a function to find all Words that have the same unique character set. Example: Input: words[] = { "may", "student", "students", "dog", "studentssess", "god", "cat", "act", "tab", "bat", "flow", "wolf", "lambs", "amy", "yam", "balms", "looped", "poodl
8 min read
k-th distinct (or non-repeating) element among unique elements in an array.Given an integer array arr[], print kth distinct element in this array. The given array may contain duplicates and the output should print the k-th element among all unique elements. If k is more than the number of distinct elements, print -1.Examples:Input: arr[] = {1, 2, 1, 3, 4, 2}, k = 2Output:
7 min read
Intermediate problems on Hashing
Find Itinerary from a given list of ticketsGiven a list of tickets, find the itinerary in order using the given list.Note: It may be assumed that the input list of tickets is not cyclic and there is one ticket from every city except the final destination.Examples:Input: "Chennai" -> "Bangalore" "Bombay" -> "Delhi" "Goa" -> "Chennai"
11 min read
Find number of Employees Under every ManagerGiven a 2d matrix of strings arr[][] of order n * 2, where each array arr[i] contains two strings, where the first string arr[i][0] is the employee and arr[i][1] is his manager. The task is to find the count of the number of employees under each manager in the hierarchy and not just their direct rep
9 min read
Longest Subarray With Sum Divisible By KGiven an arr[] containing n integers and a positive integer k, he problem is to find the longest subarray's length with the sum of the elements divisible by k.Examples:Input: arr[] = [2, 7, 6, 1, 4, 5], k = 3Output: 4Explanation: The subarray [7, 6, 1, 4] has sum = 18, which is divisible by 3.Input:
10 min read
Longest Subarray with 0 SumGiven an array arr[] consisting of both positive and negative integers, the objective is to find the length of the longest subarray whose elements sum is zero. A subarray is a contiguous part of an array, formed by selecting one or more consecutive elements while maintaining their original order.Exa
8 min read
Longest Increasing consecutive subsequenceGiven N elements, write a program that prints the length of the longest increasing consecutive subsequence. Examples: Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 6 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. Input : a[] = {6
10 min read
Count Distinct Elements In Every Window of Size KGiven an array arr[] of size n and an integer k, return the count of distinct numbers in all windows of size k. Examples: Input: arr[] = [1, 2, 1, 3, 4, 2, 3], k = 4Output: [3, 4, 4, 3]Explanation: First window is [1, 2, 1, 3], count of distinct numbers is 3. Second window is [2, 1, 3, 4] count of d
10 min read
Design a data structure that supports insert, delete, search and getRandom in constant timeDesign a data structure that supports the following operations in O(1) time.insert(x): Inserts an item x to the data structure if not already present.remove(x): Removes item x from the data structure if present. search(x): Searches an item x in the data structure.getRandom(): Returns a random elemen
5 min read
Subarray with Given Sum - Handles Negative NumbersGiven an unsorted array of integers, find a subarray that adds to a given number. If there is more than one subarray with the sum of the given number, print any of them.Examples: Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33Output: Sum found between indexes 2 and 4Explanation: Sum of elements betwee
13 min read
Implementing our Own Hash Table with Separate Chaining in JavaAll data structure has their own special characteristics, for example, a BST is used when quick searching of an element (in log(n)) is required. A heap or a priority queue is used when the minimum or maximum element needs to be fetched in constant time. Similarly, a hash table is used to fetch, add
10 min read
Linear Probing in Hash TablesIn Open Addressing, all elements are stored in the hash table itself. So at any point, size of table must be greater than or equal to total number of keys (Note that we can increase table size by copying old data if needed).Insert(k) - Keep probing until an empty slot is found. Once an empty slot is
9 min read
Maximum possible difference of two subsets of an arrayGiven an array of n-integers. The array may contain repetitive elements but the highest frequency of any element must not exceed two. You have to make two subsets such that the difference of the sum of their elements is maximum and both of them jointly contain all elements of the given array along w
15+ min read
Sorting using trivial hash functionWe have read about various sorting algorithms such as heap sort, bubble sort, merge sort and others. Here we will see how can we sort N elements using a hash array. But this algorithm has a limitation. We can sort only those N elements, where the value of elements is not large (typically not above 1
15+ min read
Smallest subarray with k distinct numbersWe are given an array consisting of n integers and an integer k. We need to find the smallest subarray [l, r] (both l and r are inclusive) such that there are exactly k different numbers. If no such subarray exists, print -1 and If multiple subarrays meet the criteria, return the one with the smalle
14 min read