Open In App

Check if max occurring character of one string appears same no. of times in other

Last Updated : 15 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings, we need to take the character which has the maximum occurrence in the first string, and then we have to check if that particular character is present in the second string the same number of times as it is present in the first string.
Examples: 
 

Input : s1 = "sssgeek", s2 = "geeksss"
Output : Yes
Max occurring character in s1 is
's'. It occurs same number of times
in s2.

Input :  geekyarticle
         gfggfggfg
Output : No

 

Store counts of characters in the first string and finds the maximum count. Now traverse through the second string and check if the maximum occurring character occurs the same number of times or not.

Algorithm:

  • Create an array count of size 256 to keep the count of individual characters and initialize the array as 0.
  • Iterate through the first string s1 and for each character, increment the count of that character in the count array.
  • Find the maximum occurring character and its count in the count array using a loop:
                   a. Initialize variables mx_cnt and mx_chr to 0 and NULL character, respectively.
                   b. Iterate through the count array and for each character, if its count is greater than mx_cnt, update                                      mx_cnt and mx_chr to the count and the character, respectively.
  • Iterate through the second string s2 and for each character, if it matches mx_chr, decrement mx_cnt.
  • If mx_cnt is 0, return 1 to indicate that the maximum occurring character in the first string is present in the second string the same number of times as it occurs in the first string.
  • If mx_cnt is not 0, return 0 to indicate that the condition is not met.

Below program to illustrate the above problem
 

C++




// C++ program to check the problem
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ASCIISIZE 256
 
int match(string s1, string s2)
{
    // Create array to keep the count of individual
    // characters and initialize the array as 0
    int count[ASCIISIZE] = { 0 };
 
    // Construct character count array from the input
    // string.
    for (int i = 0; i < s1.length(); i++)
        count[s1[i]]++;
 
    // Count occurrences of maximum occurring character
    int mx_cnt = 0, mx_chr;
    for (int i = 0; i < ASCIISIZE; i++) {
        if (count[i] > mx_cnt) {
            mx_cnt = count[i];
            mx_chr = i;
        }
    }
 
    // look if that character is present, the same
    // number of times it is present in second string
    for (int i = 0; i < s2.length(); i++)
        if (mx_chr == s2[i])
            mx_cnt--;
     
    // check if sum is greater or equal to number
    // return 1
    if (mx_cnt == 0)
        return 1;
}
 
// Driver program to test the above function
int main()
{
    string s1 = "geekforgeeks", s2 = "geekisgeeky";
    if (match(s1, s2))
        cout << "Yes ";
    else
        cout << "No";
 
    return 0;
}


Java




// Java program to check the problem
import java.io.*;
public class GFG
{
static int ASCIISIZE = 256;
static int match(String s1,    
                 String s2)
{
// Create array to keep the
// count of individual characters
// and initialize the array as 0
int count[] = new int[ASCIISIZE];
 
// Construct character count
// array from the input string.
char []s3 = s1.toCharArray();
for (int i = 0; i < s3.length; i++)
    count[s3[i]]++;
 
// Count occurrences of
// maximum occurring character
int mx_cnt = 0;
int mx_chr = 0;
for (int i = 0; i < ASCIISIZE; i++)
{
    if (count[i] > mx_cnt)
    {
        mx_cnt = count[i];
        mx_chr = i;
    }
}
 
// look if that character is
// present, the same number
// of times it is present in
// second string
char []s4 = s2.toCharArray();
for (int i = 0; i < s4.length; i++)
    if (mx_chr == s4[i])
        mx_cnt--;
 
// check if sum is greater or
// equal to number return 1
if (mx_cnt == 0)
    return 1;
else
    return 0;
}
 
// Driver Code
public static void main(String[] args)
{
    String s1 = "geekforgeeks",
           s2 = "geekisgeeky";
    int p = match(s1, s2);
    if (p == 1)
        System.out.println("Yes ");
    else
        System.out.println("No");
}
}
 
// This code is contributed
// by ChitraNayal


Python3




# Python3 program to
# check the problem
 
# define function for Check
# if max occurring character
# of one string appears same
# no. of times in other
def match(s1, s2) :
 
    # declare empty list
    count_list = []
 
    # iterate through each
    # character of the string
    for char in s1 :
         
        # find occurrence of
        # the character
        count = s1.count(char)
         
        # append tuple value
        # to the list
        count_list.append((count,char))
 
    # return tuple of max count
    max_occ = max(count_list)
 
    # store max count in mx_cnt
    mx_cnt = max_occ[0]
 
    # store max count
    # character in mx_chr
    mx_chr = max_occ[1]
 
    # look if max count character
    # is present in s1, the same
    # number of times it is present
    # in second string s2 or not
    # if present return True
    # otherwise False.
    if mx_cnt == s2.count(mx_chr) :
        return True
    else :
        return False
 
# Driver Code
if __name__ == "__main__" :
     
    s1 = "geeksforgeeks"
    s2 = "geekisgeeky"
 
    if match(s1,s2) :
        print("Yes")
    else :
        print("No")
         
# This code is contributed
# by Ankit Rai


C#




// C# program to check the problem
using System;
 
class GFG
{
static int ASCIISIZE = 256;
static int match(String s1,
                 String s2)
{
// Create array to keep the
// count of individual characters
// and initialize the array as 0
int []count = new int[ASCIISIZE];
 
// Construct character count                                    
// array from the input string.
for (int i = 0; i < s1.Length; i++)
    count[s1[i]]++;
 
// Count occurrences of
// maximum occurring character
int mx_cnt = 0;
int mx_chr = 0;
for (int i = 0; i < ASCIISIZE; i++)
{
    if (count[i] > mx_cnt)
    {
        mx_cnt = count[i];
        mx_chr = i;
    }
}
 
// look if that character is
// present, the same number
// of times it is present
// in second string
for (int i = 0; i < s2.Length; i++)
    if (mx_chr == s2[i])
        mx_cnt--;
 
// check if sum is greater
// or equal to number return 1
if (mx_cnt == 0)
    return 1;
else
    return 0;
}
 
// Driver Code
public static void Main()
{
    String s1 = "geekforgeeks",
           s2 = "geekisgeeky";
    int p = match(s1, s2);
    if (p == 1)
        Console.Write("Yes ");
    else
        Console.Write("No");
}
}
 
// This code is contributed
// by ChitraNayal


Javascript




<script>
 
// Javascript program to check the problem
     
    let ASCIISIZE = 256;
function match(s1,s2)
{
    // Create array to keep the
// count of individual characters
// and initialize the array as 0
let count = new Array(ASCIISIZE);
for(let i=0;i<ASCIISIZE;i++)
{
    count[i]=0;
}
// Construct character count
// array from the input string.
let s3 = s1.split("");
for (let i = 0; i < s3.length; i++)
    count[s3[i]]++;
   
// Count occurrences of
// maximum occurring character
let mx_cnt = 0;
let mx_chr = 0;
for (let i = 0; i < ASCIISIZE; i++)
{
    if (count[i] > mx_cnt)
    {
        mx_cnt = count[i];
        mx_chr = i;
    }
}
   
// look if that character is
// present, the same number
// of times it is present in
// second string
let s4 = s2.split("");
for (let i = 0; i < s4.length; i++)
    if (mx_chr == s4[i])
        mx_cnt--;
   
// check if sum is greater or
// equal to number return 1
if (mx_cnt == 0)
    return 1;
else
    return 0;
}
 
// Driver Code
let s1 = "geekforgeeks",
           s2 = "geekisgeeky";
let p = match(s1, s2);
if (p == 1)
    document.write("Yes ");
else
    document.write("No");
     
     
// This code is contributed by avanitrachhadiya2155
 
</script>


Output: 

Yes

 

Time Complexity: O(m + n), where m is the size of string s1 and n is the size of string s2. 

Auxiliary Space: O(256), no extra space required, so it is a constant.



Similar Reads

Find the element that appears once in an array where every other element appears twice
Given an array of integers. All numbers occur twice except one number which occurs once. Find the number in O(n) time &amp; constant extra space. Example : Input: arr[] = {2, 3, 5, 4, 5, 3, 4}Output: 2 Approach (Brute-force): One solution is to check every element if it appears once or not. Once an element with a single occurrence is found, return
20 min read
Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
Given two strings, the task is to check whether the frequencies of a character(for each character) in one string are multiple or a factor in another string. If it is, then output "YES", otherwise output "NO". Examples: Input: s1 = "aabccd", s2 = "bbbaaaacc" Output: YES Frequency of 'a' in s1 and s2 are 2 and 4 respectively, and 2 is a factor of 4 F
6 min read
Lengths of maximized partitions of a string such that each character of the string appears in one substring
Given string str of lowercase alphabets, split the given string into as many substrings as possible such that each character from the given string appears in a single substring. The task is to print the length of all such partitions. Examples: Input: str = "acbbcc"Output: 1 5Explanation:Possible partitions where each character of the strings occurs
8 min read
Maximized partitions of a string such that each character of the string appears in one substring
Given a string S, split the given string into as many substrings as possible such that each character from the given string appears in a single substring and print all these possible parts. The task is to print those substrings. Examples: Input: S = "ababcbacadefegdehijhklij" Output: ababcbaca defegde hijhklij Explanation: a, b, c are only present
8 min read
Longest subsequence where every character appears at-least k times
Given a string and a number k, find the longest subsequence of a string where every character appears at-least k times. Examples: Input: str = "geeksforgeeks", k = 2Output: geeksgeeksExplanation: Every character in the output subsequence appears at-least 2 times. Input : str = "aabbaabacabb", k = 5Output : aabbaabaabb Method 1 (Brute force): We can
12 min read
Two odd occurring elements in an array where all other occur even times
Given an array where all elements appear even number of times except two, print the two odd occurring elements. It may be assumed that the size of array is at-least two. Examples: Input : arr[] = {2, 3, 8, 4, 4, 3, 7, 8} Output : 2 7 Input : arr[] = {15, 10, 10, 50 7, 5, 5, 50, 50, 50, 50, 50} Output : 7 15 Simple solution : Approach : A simple sol
19 min read
Check if a character is only occurring as one single contiguous substring or not
Given string str of length N. The task is to determine whether a character is only occurring as a single contiguous substring or not i.e., there should not exist any other alphabet characters in between two same alphabets in the string. Examples: Input: "aAa"Output: FalseExplanation: There exists 'A' in between 'a' and 'a'. Hence "aa" becomes disco
5 min read
Count substrings with each character occurring at most k times
Given a string S. Count number of substrings in which each character occurs at most k times. Assume that the string consists of only lowercase English alphabets. Examples: Input : S = ab k = 1 Output : 3 All the substrings a, b, ab have individual character count less than 1. Input : S = aaabb k = 2 Output : 12 Substrings that have individual chara
16 min read
Number of substrings with each character occurring even times
Given a string S consisting of N lowercase alphabets, the task is to count the number of substrings whose frequency of each character is even. Examples: Input: S = "abbaa"Output: 4Explanation:The substrings having frequency of each character is even are {"abba", "aa", "bb", "bbaa"}.Therefore, the count is 4. Input: S = "geeksforgeeks"Output: 2 Brut
14 min read
Map every character of one string to another such that all occurrences are mapped to the same character
Given two strings s1 and s2, the task is to check if characters of the first string can be mapped with the character of the second string such that if a character ch1 is mapped with some character ch2 then all the occurrences of ch1 will only be mapped with ch2 for both the strings. Examples: Input: s1 = "axx", s2 = "cbc" Output: Yes 'a' in s1 can
8 min read
Article Tags :
Practice Tags :