Suppose we have a string s. We have to check whether the occurrences of each character in s is prime or not
So, if the input is like s = "apuuppa", then the output will be True as there are two 'a's, three 'p's and two 'u's.
To solve this, we will follow these steps −
- freq := a map containing all characters and their frequencies
- for each char in freq, do
- if freq[char] > 0 and freq[char] is not prime, then
- return False
- if freq[char] > 0 and freq[char] is not prime, then
- return True
Let us see the following implementation to get better understanding −
Example Code
from collections import defaultdict def isPrime(num): if num > 1: for i in range(2, num): if num % i == 0: return False return True return False def solve(s): freq = defaultdict(int) for i in range(len(s)): freq[s[i]] += 1 for char in freq: if freq[char] > 0 and isPrime(freq[char]) == False: return False return True s = "apuuppa" print(solve(s))
Input
"apuuppa"
Output
True