Home › Interview Questions › Which algorithm counts the occurrences of the char…

Which algorithm counts the occurrences of the characters 's', 'B', and 'C' in a given string?

🟡 Medium Coding Junior level
1Times asked
Jul 2026Last seen
Jul 2026First seen

💡 Model Answer

To count the occurrences of specific characters in a string, you can iterate through each character once and maintain a counter for each target character. A simple approach uses a dictionary (or hash map) where keys are the characters to count and values are the counts. Initialize the dictionary with the target characters set to zero. Then, for each character in the input string, check if it is one of the target keys; if so, increment its count. After the loop, the dictionary holds the final counts.

Time complexity: O(n), where n is the length of the string, because each character is examined exactly once. Space complexity: O(1) for the dictionary, since it stores a fixed number of keys (three in this case). This method is efficient and works for any string length. Example: For input "IAEBBCC", the algorithm would produce counts {"s":0, "B":2, "C":2}. If you need the output in a specific format like "B2 C2", you can format the dictionary accordingly after counting.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.

Get Assisting AI — Starts at ₹500