Count occurrences of each character in a String

ยท

5 min read

Write a program which prints the occurrences of each character in a string. It should not print duplicate characters. Below given example of input-output that demonstrates how to print the answer.

Example:

Input: aabbddbad
Output: 
a : 3    b : 3    c : 3

In the above example for the input "aabbddbad" we can see that a comes three times, b comes three times and d comes three times.

Approach:

For this problem, I'm telling you the best possible solution of O(n) time complexity. So for that solution, we will use a data structure called HashMap. It stores data in key-value pair. Let me give you a quick example Suppose you have Four subjects ( Maths, Science, Computer Science, English), and for each subject, you got marks as 69, 80, 99, 57. So now you can store the marks for each subject in such a way that when you want to see the marks of say maths you can look for it in the hashmap for which value it's pointing to. You can learn more about HashMaps but a basic idea of it would be helpful enough for this problem.

Now let's get back to our original problem. So we have a String, and what we'll do is we will create a HashMap<Character, Integer> that points characters to their count or no.of occurrences in the string and then we will iterate over the string and whenever we find a new character we will add it to the HashMap and set its default counter to 1 and when next time we find the same character we will update the count by 1. for example in our example input-output "aabbddbad" we first get a 'a' so we add it to the HashMap with a default value of 1 and when in the second iteration we get the same character 'a' again we update the count by 1 so the value becomes 2 (since it occurred in the string two times by now). The same will be done for other characters present in the string as well.

I hope you got the point and it will be more clear when we see the code.

Code :

import java.util.*;

class CountChars {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        countChar(str);
    }

    static void countChar(String str) {
        HashMap<Character, Integer> map = new HashMap<>();
        int length = str.length();
        for (int i = 0; i < length; i++) {
            char c = str.charAt(i);
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        for (Character key : map.keySet()) {
            System.out.print(key + " : " + map.get(key) + "\t");
        }
    }

}

Explanation of code:

So here at first in the main function we are taking an input string with the help of the Scanner class, next we are calling a function named countChar which is going to give us the count of occurrences of each character in the given string, and we are sending the input string as parameter.

Now let's come to the countChar method, inside the method we are first creating a hashmap that will store characters as keys and Integers as values. then we are also storing the length of our input in length variable.

Then we are running a for loop to iterate the string and inside the loop first we are taking the character at the ith index, then comes the most important part adding it to the hashmap, generally to add a key we use map.put(key,value) to add a new key and map.get(key) to get the value of a particular key but look at it carefully. what we are doing is we are adding c (character at the ith index) to the map and we are using another method map.getOrDefault(key, default value).

  map.put(c, map.getOrDefault(c, 0) + 1);

map.getOrDefault(key, default value), what this method does is it returns you the value of the provided key from the map or returns a default value if it is not found. So when we try to add a new character to the map which is not there in the map we are returning a default value of zero in the value parameter of the map.put() method, but since we are adding it to the map so that means this is the first time this character occurred in the string so we add 1 with the default value of 0. and the second time when we found the same character what this line of code will do is it will add the same character in the map but now the getOrDefault() method for this character will return us 1 since it was already added previously so with the default value of 1 we are adding another 1 which makes it 2 so in our second occurrence of that character its value will be overridden by 2 and keep on incrementing when it occurs in the future.

this was the most important part of this whole code snippet.

Now finally we are printing the answer from our hashmap. for this section of our method we are using a for-in loop and it will iterate through the keys of the hashmap, map.keySet() method does exactly the same it gives us all the keys as a Set. and finally we are printing the answer from the hashmap in the given format of our output (which can be subjected to any change depending on your specific requirements).

Time Complexity:

The time complexity of this solution would be O(n) since we are using only loop to iterate over the hashmap that's it.

So that was a pretty simple solution. I hope you understood it properly you can now try it yourself in any ide so that you get a good grasp of it. and you can even comment down your queries or any suggestions you would like to give me regarding this blog. I am looking forward to it and do follow me on other socials to learn more about such coding and programming-related topics. Thank you.


Youtube Twitter

ย