Counting Characters in a String
def count_characters(s):
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
return counts
# Example usage:
input_string = "hello world"
result = count_characters(input_string)
print("Character counts:")
for char, count in result.items():
print(f"'{char}': {count}")
If you need to keep a counter of characters, a common mistake is to say that the space complexity required for the counter is O(n). The space required for a counter of a string of latin characters is O(1) not O(n). This is because the upper bound is the range of characters, which is usually a fixed constant of 26. The input set is just lowercase Latin characters.