easy +10 pts

Most Common Character

Find the character that appears most often in a string, with ties broken by first occurrence.

Write a function `most_common_character(s: str) -> str` that takes a string `s` and returns the character that appears most frequently in `s`. If there are multiple characters with the same highest frequency, return the one that appears first in the string. - The input string may contain any printable ASCII characters (letters, digits, punctuation, spaces). - The string is case-sensitive; for example, 'a' and 'A' are different characters. - You may assume the string is not empty.

Constraints

- 1 <= len(s) <= 10^5 - The function should run in O(n) time and O(k) space, where k is the number of distinct characters (bounded by number of distinct characters).

Example

>>> most_common_character('aabbbcc')
'b'
>>> most_common_character('abracadabra')
'a'
>>> most_common_character('hello world')
'l'
>>> most_common_character('aabbcc')
'a'
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Count the occurrences of each character using a dictionary.
Keep track of the current maximum count and the character that achieved it.
If a character's count exceeds the current max, update the answer. If it equals the max, do not update, because we want the first occurrence.
Iterate through the string in order to preserve first occurrence tie-breaking.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.