Given an array letters of lowercase English letters, count the occurrences of each letter without using an external map or any extra space that scales with the input size.
Return the result as a list of [letter, count] pairs, one for each letter that appears at least once. The pairs must be sorted alphabetically by letter.
You may only use a fixed amount of auxiliary space, meaning constant space that does not depend on the size of the input.
Function Signature
def count_letters(letters: list[str]) -> list[list]:
Rules
-
Each element of
letters
is a one-character string.
-
Each pair in the result is
[letter, count]
, where
letter
is a one-character string and
count
is an integer of at least 1.
-
Letters that do not appear in the input are left out of the result.
-
Pairs are ordered by letter, from
"a"
to
"z"
.
Constraints
-
1 <= len(letters) <= 10^5
-
letters[i]
is a lowercase English letter,
"a"
to
"z"
.
Examples
Input: letters = ["a","b","a","c","b","a"]
Output: [["a",3],["b",2],["c",1]]
The letter "a" is at indices 0, 2 and 5, "b" is at indices 1 and 4, and "c" is at index 3. The pairs are listed alphabetically.
Input: letters = ["z","z","z","a","a"]
Output: [["a",2],["z",3]]
"z" occurs three times and "a" twice. The output lists "a" first even though "z" appears first in the input, because pairs are ordered by letter.
Input: letters = ["q"]
Output: [["q",1]]
A single letter produces a single pair with count 1.