Find the number of occurrences of a character upto preceding position

11 Jun, 2021
Given a string S of length N and an integer P(1≤P≤N) denoting the position of a character in the string. The task is to find the number of occurrences of the character present at the position P upto P-1 index.
Examples: 
Input : S = “ababababab”, P = 9 Output : 4 Character at P is ‘a’. Number of occurrences of ‘a’ upto 8th index is 4
Input : S = “geeksforgeeks”, P = 9 Output : 1
Naive Approach :A naive approach is to iterate over the string till Position-1 searching for a similar character. Whenever a similar character occurs increment counter variable by one. 
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// CPP program to find the number of occurrences// of a character at position P upto p-1#include <bits/stdc++.h>using namespace std; // Function to find the number of occurrences// of a character at position P upto p-1int Occurrence(string s, int position){    int count = 0;    for (int i = 0; i < position - 1; i++)        if (s[i] == s[position - 1])            count++;     // Return the required count    return count;} // Driver codeint main(){    string s = "ababababab";     int p = 9;     // Function call    cout << Occurrence(s, p);     return 0;}
// Java program to find the number of occurrences// of a character at position P upto p-1class GFG{ // Function to find the number of occurrences// of a character at position P upto p-1static int Occurrence(String s, int position){    int count = 0;    for (int i = 0; i < position - 1; i++)        if (s.charAt(i) == s.charAt(position - 1))            count++;     // Return the required count    return count;} // Driver codepublic static void main(String[] args){    String s = "ababababab";     int p = 9;     // Function call    System.out.println(Occurrence(s, p));}} // This code is contributed by 29AjayKumar
# Python3 program to find the# number of occurrences of# a character at position P upto p-1 # Function to find the number of occurrences# of a character at position P upto p-1def Occurrence(s, position):    count = 0    for i in range(position - 1):        if (s[i] == s[position - 1]):            count += 1     # Return the required count    return count # Driver codes = "ababababab"; p = 9 # Function callprint(Occurrence(s, p)) # This code is contributed by Mohit Kumar
// C# program to find the number of occurrences// of a character at position P upto p-1using System;     class GFG{ // Function to find the number of occurrences// of a character at position P upto p-1static int Occurrence(String s, int position){    int count = 0;    for (int i = 0; i < position - 1; i++)        if (s[i] == s[position - 1])            count++;     // Return the required count    return count;} // Driver codepublic static void Main(String[] args){    String s = "ababababab";     int p = 9;     // Function call    Console.WriteLine(Occurrence(s, p));}} // This code is contributed by PrinciRaj1992
<script>// Javascript program to find the number of occurrences// of a character at position P upto p-1 // Function to find the number of occurrences// of a character at position P upto p-1function Occurrence(s,position){    let count = 0;    for (let i = 0; i < position - 1; i++)        if (s[i] == s[position - 1])            count++;       // Return the required count    return count;} // Driver codelet s = "ababababab";   let p = 9; // Function calldocument.write(Occurrence(s, p));  // This code is contributed by unknown2108</script>
4
 
Time Complexity : O(N) for each query.
Efficient Approach: In case, if there are multiple such queries and we are given a unique index P for every query then an efficient approach is to use a frequency array for storing the character count in each iteration of the string.
Below is the implementation of the above approach : 
C++
Java
Python3
C#
Javascript
// CPP program to find the number of occurrences// of a character at position P upto p-1#include <bits/stdc++.h>using namespace std; // Function to find the number of occurrences// of a character at position P upto p-1int countOccurrence(string s, int position){    int alpha[26] = { 0 }, b[s.size()] = { 0 };     // Iterate over the string    for (int i = 0; i < s.size(); i++) {        // Store the Occurrence of same character        b[i] = alpha[(int)s[i] - 97];         // Increase its frequency        alpha[(int)s[i] - 97]++;    }     // Return the required count    return b[position - 1];} // Driver codeint main(){    string s = "ababababab";     int p = 9;     // Function call    cout << countOccurrence(s, p);     return 0;}
// Java program to find the number of occurrences// of a character at position P upto p-1import java.util.*; class GFG{ // Function to find the number of occurrences// of a character at position P upto p-1static int countOccurrence(String s, int position){    int []alpha = new int[26];    int []b = new int[s.length()];     // Iterate over the string    for (int i = 0; i < s.length(); i++)    {        // Store the Occurrence of same character        b[i] = alpha[(int)s.charAt(i) - 97];         // Increase its frequency        alpha[(int)s.charAt(i) - 97]++;    }     // Return the required count    return b[position - 1];} // Driver codepublic static void main(String[] args){    String s = "ababababab";     int p = 9;     // Function call    System.out.println(countOccurrence(s, p));}} // This code is contributed by 29AjayKumar
# Python3 program to find the number of occurrences# of a character at position P upto p-1 # Function to find the number of occurrences# of a character at position P upto p-1def countOccurrence(s, position):    alpha = [0] * 26    b = [0] * len(s)         # Iterate over the string    for i in range(0, len(s)):                 # Store the Occurrence of same character        b[i] = alpha[ord(s[i]) - 97]         # Increase its frequency        alpha[ord(s[i]) - 97] = alpha[ord(s[i]) - 97] + 1     # Return the required count    return b[position - 1] # Driver codes = "ababababab" p = 9 # Function callprint(countOccurrence(s, p)) # This code is contributed by Sanjit_Prasad
// C# program to find the number of occurrences// of a character at position P upto p-1using System;     class GFG{ // Function to find the number of occurrences// of a character at position P upto p-1static int countOccurrence(String s, int position){    int []alpha = new int[26];    int []b = new int[s.Length];     // Iterate over the string    for (int i = 0; i < s.Length; i++)    {        // Store the Occurrence of same character        b[i] = alpha[(int)s[i] - 97];         // Increase its frequency        alpha[(int)s[i] - 97]++;    }     // Return the required count    return b[position - 1];} // Driver codepublic static void Main(String[] args){    String s = "ababababab";     int p = 9;     // Function call    Console.WriteLine(countOccurrence(s, p));}} // This code is contributed by PrinciRaj1992
<script> // Javascript program to find the number of occurrences// of a character at position P upto p-1 // Function to find the number of occurrences// of a character at position P upto p-1function countOccurrence(s, position){    let alpha = new Array(26);    for(let i = 0; i < 26; i++)    {        alpha[i] = 0;    }    let b = new Array(s.length);      // Iterate over the string    for(let i = 0; i < s.length; i++)    {                 // Store the Occurrence of same character        b[i] = alpha[s[i].charCodeAt(0) - 97];          // Increase its frequency        alpha[s[i].charCodeAt(0) - 97]++;    }      // Return the required count    return b[position - 1];} // Driver codelet s = "ababababab"; p = 9; // Function calldocument.write(countOccurrence(s, p)); // This code is contributed by patel2127 </script>
4
 
mohit kumar 29
shubham_singh
29AjayKumar
princiraj1992
Sanjit_Prasad
nidhi_biet
unknown2108
patel2127
frequency-counting
prefix
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.