COUNTFREQ - Editorial

Problem Link - Get Characters Frequency

Problem Statement

You are given a string of size N. Count the number of distinct characters in it and also the frequency of each character.

Approach

To solve this, process each character of the string one by one while keeping track of their occurrences. This can be efficiently done using a mapping structure (such as a dictionary or hashmap), where the key is the character and the value is its frequency. After processing the string, the total number of keys in the mapping represents the number of distinct characters. For each character, subtract 1 from its frequency to meet the output requirement. Finally, display the count of distinct characters and their adjusted frequencies.

Time Complexity

The time complexity is O(N), where N is the length of the string, as each character is processed once.

Space Complexity

The space complexity is O(D, where D is the number of distinct characters in the string, due to the space used for the mapping structure.