You are given a string ‘S’ of length ‘N’ representing an integer.
Beauty of a string is the difference between the frequency of the most frequently occurring character and the least frequently occurring character.
You must return the sum of beauty of all substrings of string ‘S’.
A substring is a string formed after deleting zero or more characters from both ends of a string.
Input:
S = “hello"
Output:
5
Explanation: The following substring ‘hell’, ‘ell’, ‘llo’, ‘ello’, and ‘hello’ has the beauty of 1. Hence we return 5.
The first line of the input will contain an integer ‘N’ denoting the length of the string ‘S’.
The next line contains the string ’S’.
Output is printed on a separate line.
You don’t need to print anything. Just implement the given function.
4
aaaa
0
For test case one:
Input:
S = 'aaaa', N = 4
Output:
0
Explanation: All substrings have the same character. Hence all the substrings have a beauty of 0.
Hence we return 0.
8
tortoise
9
1 <= N <= 500
’S’ consists of lowercase English letters.
Time Limit: 1 sec
Can you solve this in O(N) time?
Simulate the problem statement.
Approach:
Algorithm:
Function int sumOfBeauty(string S):
Time Complexity: O( N^2* max(N, K) ), Where 'N' is the string 'S' length and 'K' is the number of lowercase English letters.
We are generating all substrings, which takes a time complexity of O(N^2), and for each substring, we check the frequency of each character. Hence, the overall time complexity will be O(N^2 * K).
O( N^3 ), Where ‘N’ is the string ‘S’ length.
We are taking O( N^3 ) extra space for storing the substrings. Hence, the overall space complexity will be O( N^3 ).