Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Classify strings from an array using Custom 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
Classify strings from an array using Custom Hash Function

D

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

Similar Reads

    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
    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 ar
    2 min read
    Hashing Notes for GATE Exam [2024]
    Hashing is a fundamental concept in computer science and plays a pivotal role in various algorithms and data structures. Aspiring candidates preparing for the GATE Exam 2024 must grasp the intricacies of hashing to tackle complex problem-solving scenarios efficiently. These notes aim to provide a co
    15+ 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