What is Character Frequency?
Character Frequency is a string-processing technique used to count how many times each character appears in a given string. It is commonly implemented using a HashMap (or dictionary) where each character is stored as a key and its occurrence count as the value.
Example
- Input String: "banana"
- Read 'b' → { b: 1 }
- Read 'a' → { b: 1, a: 1 }
- Read 'n' → { b: 1, a: 1, n: 1 }
- Read 'a' → { b: 1, a: 2, n: 1 }
- Read 'n' → { b: 1, a: 2, n: 2 }
- Read 'a' → { b: 1, a: 3, n: 2 }
The algorithm scans the string one character at a time. If the character already exists in the map, its count is increased. Otherwise, it is added with a frequency of 1.
Algorithm Steps
- Create an empty HashMap (or Dictionary).
- Traverse the string character by character.
- For each character:
- If already present, increment its count.
- Otherwise insert it with count = 1.
- Display all characters with their frequencies.
Time Complexity
- Best Case: O(n) (every character processed once).
- Worst Case: O(n) (HashMap insertion/search is O(1) on average).
Time Complexity Analysis
Character Frequency is widely used in text analysis, data compression, anagram detection, and many interview problems involving strings and hashing.