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”.
Python3
freq = [ 0 ] * 26
n = len (s)
for i in range (n):
freq[ ord (s[i]) - 97 ] + = 1
freq.sort()
for i in range ( 25 ):
if (freq[i] = = 0 ):
continue
if (freq[i] = = freq[i + 1 ]):
return False
return True
s = "abaccc"
if (check(s)):
print ("Yes")
else :
print ("No")
|
Approach : Using count() and len() methods.First find the count of each element, append the count to a list. If the count of first element of list equals to the length of list, then the frequencies are unique.
Python3
s = "aabbc"
v = []
for i in s:
if i not in v:
v.append(s.count(i))
x = []
for i in v:
if i not in x:
x.append(i)
if ( len (x) = = len (v)):
print ( "Yes" )
else :
print ( "No" )
|
Approach: using operator.countOf() method
Python3
import operator as op
s = "aabbc"
v = []
for i in s:
if i not in v:
v.append(op.countOf(s,i))
x = []
for i in v:
if i not in x:
x.append(i)
if ( len (x) = = len (v)):
print ( "Yes" )
else :
print ( "No" )
|
Time Complexity: O(N)
Auxiliary Space : O(N)
Using counter and set()
Algorithm:
- Import the Counter module from the collections package
- Convert the input string into a Counter object
- Extract the frequency of each character and store in a set
- If the length of the set is equal to the number of unique frequencies, return “Yes”
- Otherwise, return “No”
Python3
from collections import Counter
def check_freq(s):
freq = Counter(s)
freq_set = set (freq.values())
if len (freq_set) = = len ( set (s)):
return "Yes"
else :
return "No"
s = "abaccc"
print (check_freq(s))
|
Complexity analysis:
Time complexity: The Counter function has a time complexity of O(N) where N is the length of the string. The set function also has a time complexity of O(N). Therefore, the overall time complexity of the code is O(N).
Space complexity: The space complexity of the code is O(N) because we are creating a Counter object and a set object, both of which can store up to N elements.
Last Updated :
23 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...