Python | Check if frequencies of all characters of a string are different

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”.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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"

chevron_right


Output:

Yes


My Personal Notes arrow_drop_up

Computer Science enthusiast

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.