Sum of frequencies of characters of a string present in another string


In this article, we are going to explore an interesting problem related to string manipulation in C++. The problem statement is "Sum of frequencies of characters of a string present in another string". This problem provides a great opportunity to enhance your understanding of string operations, character frequency calculation, and the concept of mapping in C++.

Problem Statement

Given two strings, the task is to find the sum of frequencies of characters of the first string that are present in the second string.

C++ Solution Approach

To solve this problem, we will first create frequency maps for both strings using hash maps. A frequency map is a map where each character in the string maps to the count of that character in the string. We'll use the STL unordered_map for this purpose. After creating the frequency maps, we will iterate over the frequency map of the first string, and for each character that is also present in the second string, we add its frequency to our sum.

Example

Here's the C++ code that implements this solution −

#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

int sumOfFrequencies(string str1, string str2) {
   unordered_map<char, int> freq1, freq2;
   
   for (char c : str1) {
      freq1[c]++;
   }
   
   for (char c : str2) {
      freq2[c]++;
   }
   
   int sum = 0;
   for (auto& kv : freq1) {
      if (freq2.count(kv.first)) {
         sum += kv.second;
      }
   }
   
   return sum;
}

int main() {
   string str1 = "hello", str2 = "world";
   cout << "The sum of frequencies is: " << sumOfFrequencies(str1, str2);
   return 0;
}   

Output

The sum of frequencies is: 3

Explanation with a Test Case

Let's consider the strings "hello" and "world".

When we pass these strings to the sumOfFrequencies function, it first creates the frequency maps for both strings. For "hello", the frequency map is {'h':1, 'e':1, 'l':2, 'o':1}, and for "world", the frequency map is {'w':1, 'o':1, 'r':1, 'l':1, 'd':1}.

The function then iterates over the frequency map of "hello" and for each character that is also present in "world", it adds its frequency to the sum. The common characters are 'o' and 'l', and their frequencies in "hello" are 1 and 2, respectively. So, the sum of frequencies is 3.

Therefore, the output of this program will be "The sum of frequencies is: 3".

Conclusion

This problem provides a great opportunity to understand and practice the concept of frequency mapping in C++. It's an excellent problem to improve your C++ coding skills and to understand how to handle strings and maps for problem-solving.

Updated on: 18-May-2023

441 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements