Count Character Occurrences

Easy
0/40
3 upvotes

Problem statement

Given a string 'S' of length 'N' and a character 'C', the task is to count the occurrence of the given character in the string.


Return the total number of times the character 'C' appears in the string 'S'.


For Example :
Let 'N' = 5, 'S' = "bbacb", 'C' = 'b'.
The character 'b' appears 3 times in the string "bbacb".
Therefore, the answer is 3.
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line contains the integer 'N', the length of the string 'S'.
The second line contains the string 'S' of length 'N'.
The third line contains the character 'C' to be counted.
Output Format :
Return the total count of the character 'C' in the string 'S'.
Note :
You don’t need to print anything. Just implement the given function.
Constraints :
1 <= 'N' <= 10^5
'a' <= characters in 'S' <= 'z'
'a' <= 'C' <= 'z'

Time Limit: 1 sec
Sample Input 1 :
7
abacaba
a
Sample Output 1 :
4
Explanation of sample input 1 :
The input string 'S' is "abacaba" and the character to count 'C' is 'a'.
The character 'a' appears at indices 0, 2, 4, and 6 in the string.
Thus, the total count of 'a' in "abacaba" is 4.
Therefore, the answer is 4.
Sample Input 2 :
5
hello
l
Sample Output 2 :
2
Hint

Iterate through the string and check if each character matches the given character.

Approaches (1)
Implementation

Approach:

  • Initialize a counter variable to zero.
  • Iterate through each character of the input string 'S'.
  • For each character in 'S', compare it with the given character 'C'.
  • If the characters match, increment the counter.
  • After iterating through the entire string, the value of the counter will be the total number of occurrences of 'C' in 'S'.

Algorithm:

  • Initialize a variable 'count' to 0.
  • Iterate using 'i' from 0 to 'N - 1':
    • If ( S[ i ] == C ):
      • Increment 'count' by 1.
  • Return 'count'.
Time Complexity

O(N), where 'N' is the length of the string 'S'.

We iterate through each of the 'N' characters in the string 'S' once. Thus, the overall time complexity is of the order O(N).

Space Complexity

O(1).

We only use a single integer variable 'count' for storing the result, which takes constant space. Thus, the overall space complexity is of the order O(1).

Code Solution
(100% EXP penalty)
Count Character Occurrences
Full screen
Console