Medium
Find the Most Frequent Character in a String
Description
Expanding on the concept of counting occurrences, your task is to write a function that takes a string as input and returns the most frequently occurring character in the string.
If there are multiple characters with the same highest frequency, return the one that appears first in the string.
This challenge is useful in various scenarios such as:
- Text analysis (e.g., finding the most common letter in a document).
- Optimizing algorithms by identifying frequently used elements.
- Understanding user behavior by analyzing repeated patterns.
Requirements
Input: - A non-empty string containing letters (both uppercase and lowercase).
Output: - The character that appears most frequently in the string.
If there is a tie, return the character that appears first.
Considerations:
- The function should be case-sensitive.
- Spaces and special characters should be counted as well.
- Handle edge cases such as strings with all unique characters.
Example Usage
mostFrequentChar("banana"); // Expected output: "a" mostFrequentChar("aabbbcc"); // Expected output: "b" mostFrequentChar("TechBlitz"); //Expected output: "T"
Did you know?
JavaScript was originally called "LiveScript" before being renamed to JavaScript.
Test Cases
Input:
"javascript"
Expected Output:
"a"