Given a string text, return a list of lists where each inner list contains a character and its frequency in the text.
The result should be sorted by character in ascending order (by ASCII value). Only include characters that appear at least once in text.
Function Signature
def character_histogram(text: str) -> list[list[str | int]]:
Rules
-
Each inner list has exactly two elements: the character as a one-character string, then its count as an integer.
-
Sort the pairs by character in ascending ASCII order, comparing
ord
values. A space (32) sorts before every other printable character, and uppercase letters (65 to 90) sort before lowercase letters (97 to 122).
-
Counting is case-sensitive:
'A'
and
'a'
are different characters with separate entries.
-
Every character counts, including spaces, digits and punctuation. Each distinct character appears in exactly one pair, and characters that do not occur in
text
are left out.
Constraints
-
1 <= len(text) <= 10^5
-
text
consists of printable ASCII characters (codes 32 to 126).
Examples
Input: text = "hello"
Output: [["e", 1], ["h", 1], ["l", 2], ["o", 1]]
l occurs twice and the other letters once. By ASCII value e (101) comes before h (104), l (108) and o (111), even though h is the first letter of the string.
Input: text = "aabbcc"
Output: [["a", 2], ["b", 2], ["c", 2]]
Each of a, b and c occurs exactly twice, and the three letters are already in ASCII order.
Input: text = "Bob bob"
Output: [[" ", 1], ["B", 1], ["b", 3], ["o", 2]]
The space (32) sorts first, and uppercase B (66) comes before lowercase b (98). The two cases are counted separately, so B occurs once and b three times.