I am developing an algorithm to filter and count the number of words that users query the most.
I have an array of queries consisting of strings representing the keywords that users search for in a day, for example:
const queries = [
"weather today", "openai", "javascript arrays", "weather today",
"news", "javascript arrays", "open", "javascript arrays",
"recipe", "news", "openai", "weather today"
];
Need to:
Average complexity O(n log n)
My function is writing but it is not running correctly:
function topKFrequent(queries, k) {
const freqMap = {};
for (const q of queries) {
freqMap[q] = (freqMap[q]) + 1;
}
const entries = Object.entries(freqMap);
entries.sort((a, b) => {
let countA = a[1], countB = b[1];
if (countA != countB) {
return countB - countA;
}
return a[0].localeCompare(b[0]);
});
return entries.slice(0, k).map(entry => entry[0]);
}
With:
queries – array of search strings.
k– number of most popular keywords to return.
I run the following command console.log(topKFrequent(queries, 2));
It outputs [ 'weather today', 'openai' ], and actually I was expecting ["javascript arrays", "weather today"], because "javascript arrays", and "weather today" both appear 3 times while "openai" appears exactly 2 times.
Expected result:
["javascript arrays", "weather today"]
Average complexity O(n log n)
Thanks.