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:
Sorting using trivial hash function
Next article icon

Classify strings from an array using Custom Hash Function

Last Updated : 24 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of strings arr[] consisting of N strings, the task is to categorize the strings according to the hash value obtained by adding ASCII values % 26 of the characters in the string.

Examples:

Input: arr[][] = {“geeks”, “for”, “geeks”}
Output:
geeks geeks
for
Explanation:
The hash value of string “for” is (102 + 111 + 114) % 26 = 14
The hash value of string “geeks” is (103 + 101 + 101 + 107 + 115) % 26 = 7
Therefore, two “geeks” are grouped together and “for” is kept in another group.

Input: arr[][] = {“adf”, “aahe”, “bce”, “bgdb”}
Output: 
aahe bgdb
bce
adf 
Explanation: 
The hash value of string “adf” is (97 + 100 + 102)%26 = 13
The hash value of string “aahe” is (97 + 97 + 104 + 101)%26 = 9
The hash value of string “bce” is (98 + 99 + 101)%26 = 12
The hash value of string “bgdb” is (98 + 103 + 100 + 98)%26 = 9
Therefore,  strings “aahe” and “bgdb” have same hashed value, so they are grouped together.

Approach: The idea is to use Map Data Structure for grouping together the strings with the same hash values. Follow the steps below to solve the problem:

  • Initialize a Map, say mp, to map hash values with respective strings in a vector.
  • Traverse the given array of strings and perform the following steps:
    • Calculate the hash value of the current string according to the given function.
    • Push the string into the vector with the calculated hash values of the string as key in the map mp.
  • Finally, traverse the map mp and print all the strings of respective keys.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the hash
// value of the string s
int stringPower(string s)
{
    // Stores hash value of string
    int power = 0;
    int n = s.length();
 
    // Iterate over characters of the string
    for (int i = 0; i < n; i++) {
 
        // Calculate hash value
        power = (power + (s[i])) % 26;
    }
 
    // Return the hash value
    return power;
}
 
// Function to classify the strings
// according to the given condition
void categorisation_Of_strings(
    vector<string> s, int N)
{
    // Maps strings with their strings
    // respective hash values
    map<int, vector<string> > mp;
 
    // Traverse the array of strings
    for (int i = 0; i < N; i++) {
 
        // Find the hash value of the
        // of the current string
        int temp = stringPower(s[i]);
 
        // Push the current string in
        // value vector of temp key
        mp[temp].push_back(s[i]);
    }
 
    // Traverse over the map mp
    for (auto power : mp) {
 
        // Print the result
        for (auto str : power.second) {
            cout << str << " ";
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    vector<string> arr{ "adf", "aahe",
                        "bce", "bgdb" };
    int N = arr.size();
 
    categorisation_Of_strings(arr, N);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
 
class GFG{
     
// Function to find the hash
// value of the string s
static int stringPower(String s)
{
     
    // Stores hash value of string
    int power = 0;
    int n = s.length();
    char C[] = s.toCharArray();
 
    // Iterate over characters of the string
    for(int i = 0; i < n; i++)
    {
         
        // Calculate hash value
        power = (power + (C[i])) % 26;
    }
 
    // Return the hash value
    return power;
}
 
// Function to classify the strings
// according to the given condition
static void categorisation_Of_strings(Vector<String> s,
                                      int N)
{
     
    // Maps strings with their strings
    // respective hash values
    Map<Integer, Vector<String> > mp = new HashMap<>();
     
    // Traverse the array of strings
    for(int i = 0; i < N; i++)
    {
         
        // Find the hash value of the
        // of the current string
        int temp = stringPower(s.get(i));
 
        // Push the current string in
        // value vector of temp key
        if (mp.containsKey(temp))
        {
            mp.get(temp).add(s.get(i));
        }
        else
        {
            mp.put(temp, new Vector<String>());
            mp.get(temp).add(s.get(i));
        }
    }
 
    // Traverse over the map mp
    for(Map.Entry<Integer,
           Vector<String>> entry : mp.entrySet())
    {
         
        // Print the result
        for(String str : entry.getValue())
        {
            System.out.print(str + " ");
        }
        System.out.println();
    }
}
 
// Driver code
public static void main(String[] args)
{
    String[] Sarr = { "adf", "aahe", "bce", "bgdb" };
    Vector<String> arr = new Vector<String>(
        Arrays.asList(Sarr));
    int N = arr.size();
 
    categorisation_Of_strings(arr, N);
}
}
 
// This code is contributed by abhinavjain194
 
 

Python3




# Python3 program for the above approach
 
# Function to find the hash
# value of the string s
def stringPower(s):
   
    # Stores hash value of string
    power = 0
    n = len(s)
 
    # Iterate over characters of the string
    for i in range(n):
       
        # Calculate hash value
        power = (power + ord(s[i])) % 26
 
    # Return the hash value
    return power
 
# Function to classify the strings
# according to the given condition
def categorisation_Of_strings(s, N):
   
    # Maps strings with their strings
    # respective hash values
    mp = {}
 
    # Traverse the array of strings
    for i in range(N):
       
        # Find the hash value of the
        # of the current string
        temp = stringPower(s[i])
 
        # Push the current string in
        # value vector of temp key
        if temp in mp:
            mp[temp].append(s[i])
        else:
            mp[temp] = []
            mp[temp].append(s[i])
             
    # Traverse over the map mp
    for i in sorted (mp) :
       
        # Print the result
        for str in mp[i]:
            print(str,end = " ")
        print("\n",end = "")
 
# Driver Code
if __name__ == '__main__':
    arr =  ["adf", "aahe", "bce", "bgdb"]
    N = len(arr)
    categorisation_Of_strings(arr, N)
 
    # This code is contributed by ipg2016107.
 
 

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to find the hash
// value of the string s
function stringPower(s)
{
     
    // Stores hash value of string
    var power = 0;
    var n = s.length;
 
    // Iterate over characters of the string
    for(var i = 0; i < n; i++)
    {
         
        // Calculate hash value
        power = (power + (s[i].charCodeAt(0))) % 26;
    }
 
    // Return the hash value
    return power;
}
 
// Function to classify the strings
// according to the given condition
function categorisation_Of_strings(s, N)
{
     
    // Maps strings with their strings
    // respective hash values
    var mp = new Map();
 
    // Traverse the array of strings
    for(var i = 0; i < N; i++)
    {
         
        // Find the hash value of the
        // of the current string
        var temp = stringPower(s[i]);
 
        // Push the current string in
        // value vector of temp key
        if (!mp.has(temp))
        {
            mp.set(temp, new Array());
        }
        var tmp = mp.get(temp);
        tmp.push(s[i]);
        mp.set(temp, tmp);
    }
 
    var tmp = Array();
 
    // Traverse over the map mp
    mp.forEach((value, key) => {
        tmp.push(key);
    });
 
    tmp.sort((a, b) => a - b);
 
     // Traverse over the map mp
    tmp.forEach((value) => {
         
        // Print the result
        mp.get(value).forEach(element => {
            document.write(element + " ");
        });
        document.write("<br>");
    });
}
 
// Driver Code
var arr = [ "adf", "aahe", "bce", "bgdb" ];
var N = arr.length;
 
categorisation_Of_strings(arr, N);
 
// This code is contributed by rutvik_56
 
</script>
 
 

C#




using System;
using System.Collections.Generic;
using System.Linq;
 
namespace ConsoleApp1
{
    class Program
    {
        // Function to find the hash
        // value of the string s
        static int StringPower(string s)
        {
            // Stores hash value of string
            int power = 0;
            int n = s.Length;
            char[] C = s.ToCharArray();
 
            // Iterate over characters of the string
            for (int i = 0; i < n; i++)
            {
                // Calculate hash value
                power = (power + (C[i])) % 26;
            }
 
            // Return the hash value
            return power;
        }
 
        // Function to classify the strings
        // according to the given condition
        static void CategorisationOfStrings(List<string> s,
                                            int N)
        {
            // Maps strings with their strings
            // respective hash values
            SortedDictionary<int, List<string>> mp = new SortedDictionary<int, List<string>>();
 
            // Traverse the array of strings
            for (int i = 0; i < N; i++)
            {
                // Find the hash value of the
                // of the current string
                int temp = StringPower(s[i]);
 
                // Push the current string in
                // value vector of temp key
                if (mp.ContainsKey(temp))
                {
                    mp[temp].Add(s[i]);
                }
                else
                {
                    mp[temp] = new List<string>();
                    mp[temp].Add(s[i]);
                }
            }
 
            // Traverse over the map mp
            foreach (var entry in mp)
            {
                // Print the result
                foreach (string str in entry.Value)
                {
                    Console.Write(str + " ");
                }
                Console.WriteLine();
            }
        }
 
        static void Main(string[] args)
        {
            string[] Sarr = { "adf", "aahe", "bce", "bgdb" };
            List<string> arr = new List<string>(Sarr);
            int N = arr.Count;
 
            CategorisationOfStrings(arr, N);
        }
    }
}
 
 
Output
aahe bgdb  bce  adf 

Time Complexity: O(N*M), where M is the length of the longest string.
Auxiliary Space: O(N*M)



Next Article
Sorting using trivial hash function

D

deepika_sharma
Improve
Article Tags :
  • Arrays
  • Data Structures
  • DSA
  • Hash
  • Strings
  • ASCII
  • cpp-map
Practice Tags :
  • Arrays
  • Data Structures
  • Hash
  • Strings

Similar Reads

  • Convert an Array to reduced form using Hashing
    Given an array with N distinct elements, convert the given array to a form where all elements are in the range from 0 to N-1. The order of elements is the same, i.e., 0 is placed in the place of the smallest element, 1 is placed for the second smallest element, ... N-1 is placed for the largest elem
    15+ min read
  • Sorting using trivial hash function
    We 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
  • Hash Functions and Types of Hash functions
    Hash functions are a fundamental concept in computer science and play a crucial role in various applications such as data storage, retrieval, and cryptography. A hash function creates a mapping from an input key to an index in hash table. Below are few examples. Phone numbers as input keys : Conside
    5 min read
  • What are Hash Functions and How to choose a good Hash Function?
    What is a Hash Function?A hash function is a function that converts a given large number (such as a phone number) into a smaller, practical integer value. This mapped integer value is used as an index in a hash table. In simple terms, a hash function maps a large number or string to a small integer
    4 min read
  • Sorting a Hashmap according to values
    Given the marks scored out of 100 by a student in subjects where the name of the subject is key and marks scored is the value. A HashMap is created using the subject name and respective marks as key-value pairs. The task is to sort the HashMap according to values i.e. according to marks. Example: In
    9 min read
  • Check whether array has all identical elements using Arrays.asList() and HashSet in Java
    Given an array arr[] of N elements, the task is to check whether the array have all same (identical) elements or not without using the loop. If all elements are same then print Yes otherwise print No. Examples: Input: arr[] = {2, 2, 2, 2, 2} Output: Yes The given array has all identical elements i.e
    2 min read
  • Check if an array has a majority element
    Given an array, the task is to find if the input array contains a majority element or not. An element is Examples: Input : arr[] = {2, 3, 9, 2, 2} Output : Yes A majority element 2 is present in arr[] Input : arr[] = {1, 8, 9, 2, 5} Output : No A simple solution is to traverse through the array. For
    4 min read
  • PHP | hash_algos() Function
    The hash_algos() function is an inbuilt function in PHP which is used to return a list of registered hashing algorithms. Syntax: array hash_algos( void ) Parameter: This function does not accepts any parameter. Return Value: This function returns a numerically indexed array which contains the list o
    2 min read
  • PHP | hash_hmac_algos() Function
    The hash_hmac_algos() function is an inbuilt function in PHP that is used to get the list of registered hashing algorithms suitable for the hash_hmac() function. Syntax: array hash_hmac_algos( void ) Parameters: This function does not accept any parameter. Return Value: This function returns an arra
    2 min read
  • Check if concatenation of any permutation of given list of arrays generates the given array
    Given an array arr[] of N distinct integers and a list of arrays pieces[] of distinct integers, the task is to check if the given list of arrays can be concatenated in any order to obtain the given array. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {1, 2, 4,
    9 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