Fundamentals/Character Counting
← PrevNext →
Implement countCharacters(s) that returns a frequency map (object/dictionary) mapping each character in s to the number of times it appears. Iterate through the string a single time, incrementing the count for each character as you go.
The result must include every distinct character that appears in s and only those characters. An empty input string yields an empty map.
Input
s: the input string
Output
A map whose keys are the distinct characters in s and whose values are the counts of how many times each character appears.
Examples
Example 1
Inputs = "hello"
Output{"h": 1, "e": 1, "l": 2, "o": 1}
Explanation: 'l' occurs twice; every other character occurs once.
Example 2
Inputs = "aaa"
Output{"a": 3}
Example 3
Inputs = ""
Output{}
Explanation: An empty string has no characters, so the map is empty.
Constraints
Run in O(n) time where n is the length of s.
Return an empty map for the empty string.