This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
145. most frequently occurring character
One possible solution in JavaScript:
function count(str) { const countMap = {}; let maxCount = 0; for (let i = 0; i < str.length; i++) { const char = str[i]; countMap[char] = (countMap[char] || 0) + 1; maxCount = Math.max(maxCount, countMap[char]); } const result = []; for (const char in countMap) { if (countMap[char] === maxCount) { result.push(char); } } return result.length === 1 ? result[0] : result;}
Explanation:
- We use an object
countMap
to map each character to its count in the string. - We also keep track of the
maxCount
of any character seen so far. - We loop through the string and update the count of each character in
countMap
. - We update
maxCount
if necessary. - Finally, we loop through
countMap
again and add any character that has count equal tomaxCount
to an arrayresult
. - If
result
has only one element, we return that element, otherwise we returnresult
itself.
The time complexity of this approach is O(n), where n is the length of the string, because we need to loop through the string once to update countMap
and maxCount
, and then loop through countMap
once again to find the characters with the max count.
The space complexity is O(k), where k is the number of distinct characters in the string, because we need to store each distinct character as a key in countMap
. In the worst case, where all characters are distinct, the space complexity is O(n).