Music Teacher: A music teacher has developed a new technique to teach the students in which unique node is identified by a lower character of English alphabet. In total there nodes in this technique from ‘a’ to ‘z’. To teach a new song the music teacher fin converts the song to string consisting of a to z then he breaks it into melodies. melody is a collection of nodes in which the frequency of each node present in melody is the same. He strictly teaches one melody in one day. You’re given the string and your task is to find and return the minimum number of days in whic teach the whole song.
Input Specification:
input1: A string representing the song string.
Output Specification:
Return the minimum number of days in which he can teach the whole song.
Example 1:
input1: “abbaabcd”
Output: 2
Explanation:
the fist melody will be “abbaab” and the second melody will be “cd” so the total number of days will be 2.
Example 2:
input1: “abcd”
Output: 1
Explanation:
the fist melody will be “abcd” so the total number of days will be 1.
Solution
Steps:
- Initialize a HashMap to store the frequency of each character (node) in the song.
- Loop through each character in the input song and count its frequency using the HashMap.
- After counting the frequencies, create a HashSet and store the unique frequencies in it.
- The size of the HashSet represents the number of distinct frequencies in the song.
- Return the size of the HashSet, which is the minimum number of days required to teach the whole song.
public static int minimum_k(String input1)
{
int[] freq = new int[26];
for (int i = 0; i < input1.length(); i++)
{
freq[input1.charAt(i) - 'a']++;
// github.com/sauravhathi
}
int count = 0;
for (int i = 0; i < 26; i++)
{
if (freq[i] != 0)
{
count++;
}
}
return count;
}
#include <iostream>
#include <unordered_map>
#include <unordered_set>
using namespace std;
int minimumK(string input1) {
unordered_map<char, int> frequencyMap;
for (char ch : input1) {
frequencyMap[ch]++;
// github.com/sauravhathi
}
unordered_set<int> distinctFrequencies;
for (const auto& pair : frequencyMap) {
distinctFrequencies.insert(pair.second);
}
return distinctFrequencies.size();
}
def minimum_k(input1):
d = {}
for i in input1:
if i in d:
d[i] += 1
# github.com/sauravhathi
else:
d[i] = 1
distinct_frequencies = set(d.values())
return len(distinct_frequencies)
Happy Learning – If you require any further information, feel free to contact me.