Sum of frequencies of characters of a string present in another string
Last Updated :
14 May, 2021
Given two strings S1 and S2 of lengths M and N respectively, the task is to calculate the sum of the frequencies of the characters of string S1 in the string S2.
Examples:
Input: S1 = “pPKf”, S2 = “KKKttsdppfP”
Output: 7
Explanation:
The character ‘p’ occurs twice in the string S2.
The character ‘P’ occurs once in the string S2.
The character ‘K’ occurs thrice in the string S2.
The character ‘f’ occurs once in the string S2.
Therefore, in total, characters of the string S1 occurs 7 times in the string S2.
Input: S1 = “geEksFOR”, S2 = “GeEksforgeEKS”
Output: 7
Naive Approach: The simplest approach is to iterate over each character of the string S1, count its frequency in the string S2.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by using Hashing. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void countTotalFrequencies(string S1, string S2)
{
set< char > bset;
for ( auto x:S1)
bset.insert(x);
int count = 0;
for ( auto x: S2)
{
if (bset.find(x) != bset.end())
count += 1;
}
cout << count << endl;
}
int main()
{
string S1 = "geEksFOR" ;
string S2 = "GeEksforgeEKS" ;
countTotalFrequencies(S1, S2);
}
|
Java
import java.util.HashSet;
class GFG{
static void countTotalFrequencies(String S1, String S2)
{
HashSet<Character> bset = new HashSet<Character>();
char [] S1arr = S1.toCharArray();
char [] S2arr = S2.toCharArray();
for ( char x : S1arr)
bset.add(x);
int count = 0 ;
for ( char x : S2arr)
{
if (bset.contains(x))
count += 1 ;
}
System.out.print(count);
}
public static void main(String[] args)
{
String S1 = "geEksFOR" ;
String S2 = "GeEksforgeEKS" ;
countTotalFrequencies(S1, S2);
}
}
|
Python3
def countTotalFrequencies(S1, S2):
bset = set (S1)
count = 0
for x in S2:
if x in bset:
count + = 1
print (count)
S1 = "geEksFOR"
S2 = "GeEksforgeEKS"
countTotalFrequencies(S1, S2)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void countTotalFrequencies( string S1,
string S2)
{
HashSet< char > bset = new HashSet< char >();
foreach ( char x in S1)
bset.Add(x);
int count = 0;
foreach ( char x in S2)
{
if (bset.Contains(x))
count += 1;
}
Console.Write(count);
}
static void Main()
{
string S1 = "geEksFOR" ;
string S2 = "GeEksforgeEKS" ;
countTotalFrequencies(S1, S2);
}
}
|
Javascript
<script>
function countTotalFrequencies(S1, S2)
{
var bset = new Set();
for ( var i = 0; i < S1.length; i++)
{
bset.add(S1[i]);
}
var count = 0;
for ( var i = 0; i < S2.length; i++)
{
if (bset.has(S2[i]))
count += 1;
}
document.write(count);
}
var S1 = "geEksFOR" ;
var S2 = "GeEksforgeEKS" ;
countTotalFrequencies(S1, S2);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...