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

Suppose we have two strings s and t, we have to select the most frequent character from s and then we have to check whether that particular character is present in t same number of times or not.

So, if the input is like s = "crosssection", t = "securesystem", then the output will be True, as the most frequent character in s is 's'. And there are same number of occurrences of 's' in t.

To solve this, we will follow these steps −

  • freq := a map containing all characters of s and their frequencies
  • max_freq_char = character in s where frequency is maximum
  • max_freq := frequency value of max_freq_char
  • if occurrences of max_freq_char in t is same as max_freq , then
    • return True
  • return False


Let us see the following implementation to get better understanding −

 Live Demo

from collections import defaultdict
def solve(s, t) :
   freq = defaultdict(int)
   for char in s :
      freq[char] += 1
   max_freq_char = max(freq, key=freq.get)
   max_freq = freq[max_freq_char]
   if max_freq == t.count(max_freq_char) :
      return True
   return False
s = "crosssection"
t = "securesystem"
print(solve(s, t))


"crosssection", "securesystem"



Updated on: 19-Jan-2021


Kickstart Your Career

Get certified by completing the course

Get Started