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”.
# 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") |
Yes
Recommended Posts:
- Sum and Product of Prime Frequencies of Characters in a String
- Python | Ways to check string contain all same characters
- Python program to check if a string contains all unique characters
- Check whether second string can be formed from characters of first string
- Python | Extract only characters from given string
- Iterate over characters of a string in Python
- Python | Return lowercase characters from given string
- Python | Splitting string to list of characters
- Python | Split string into list of characters
- Python | Splitting string to list of characters
- Python | Convert a list of characters into a string
- Python | Removing unwanted characters from string
- Concatenated string with uncommon characters in Python
- Python Counter| Find all duplicate characters in string
- Python | Split string in groups of n consecutive characters
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.



