In today's LeetCode daily challenge we were tasked to sort an string by character frequency:
Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers, return any of them.
I'm a beginner and I started learning C, I did my code and it apparently it was working, however when returning the answer in the code for the site, the output I was getting was "(NULL)".
My code is as follows:
char * frequencySort(char * s){
int dictionary[56] = { 0 }; //array that stores character frequency
int length = strlen(s);
char ans[50000] = { '\0' };
//for loop that read the string and stores character frequency
for (int i = 0; i < length; i++) {
int op = s[i]-65;
dictionary[op]++;
}
//for loop that sorts the characters in order of frequency in the ans string
for (int i = 0; i < length; i++) {
int op = 0;
for (int j = 0; j < 56; j++) {
if (dictionary[j] > dictionary[op]) {
op = j;
}
}
ans[i] = op + 65;
dictionary[op]--;
while (dictionary[op] > 0) {
ans[i + 1] = op + 65;
i++;
dictionary[op]--;
}
}
return ans;
}
I tested it in VSCode and there I could use printf my ans string normally, and it would print the correct answer, like if the input was "tree", it would print "eert", but when returning the ans string to LeetCode, it returns (NULL), can anyone explain what I'm doing wrong? Sorry for any English mistakes, it's not my first language.