Skip to content
Related Articles

Related Articles

Python | Check if frequencies of all characters of a string are different
  • Last Updated : 28 Nov, 2018

Given a string S consisting only of lowercase letters, the task is to check if the frequency of all characters of the string is unique.

Examples:

Input : abaccc
Output : Yes
‘a’  occurs two times, ‘b’ occurs once
and ‘c’ occurs three times.

Input : aabbc
Output : No
Frequency of both 'a' and 'b' are same.

Approach:
One thing to observe in this problem is that position of characters does not matter here so, simply count the frequency of characters. Go through the string and count the occurrence of all characters. Then sort the frequency array and check if consecutive elements are same and immediately print “No” else print “Yes”.




# Python program to check if frequency of
# all characters of a string are unique
    
    # creating a frequency array 
    freq =[0]*26
    
    # Finding length of s 
    n = len(s) 
    
    for i in range(n): 
    
        # counting frequency of all characters 
        freq[ord(s[i])-97] += 1
  
    # sorting the frequency array
    freq.sort()
    for i in range(25): 
    
        # checking if element is zero
        if (freq[i] == 0):
            continue
  
        # if element is non-zero
        # checking if frequencies are unique
        if (freq[i] == freq[i + 1]): 
            return False
  
    return True
    
# Driver code 
s ="abaccc"
  
if(check(s)): 
    print("Yes"
else
    print("No"


Output:

Yes



My Personal Notes arrow_drop_up
Recommended Articles
Page :