Queries to find the count of characters preceding the given location

Given a string S of length N containing only lower case letters. Also, given Q queries where each query consists of an integer P such that 1≤ P ≤ N. The task is to find the count of occurrences of the same letter preceding the given location P.

Examples :

Input: S = "abacsddaa", Q[] = {9, 3}
Output:
3
1
For first query, P = 9, character at 9th location is 'a'.
The number of occurrences of 'a' before P i.e. 9 is three.

Similarly, for P = 3, 3rd character is 'a'.
The number of occurrences of 'a' before P. i.e. 3 is one.

Naive approach For each query Qi which gives position ‘p’, run a loop from 1 to ‘p-1’ and check whether element present at that index is equal to element at index ‘p’, if it is true than increase the value of counter variable by 1. After completion of loop print the value of the counter variable in a new line.



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
  
int Count(string s, int pos )
{
    // returns character at index pos - 1 
    int c = s[pos - 1] ;
    int counter = 0 ;
    for (int i = 0; i < pos-1; i++ ) 
    {
        if(s[i] == c) 
            counter = counter + 1;
    }
    return counter;
}
  
// Driver Code 
int main()
{
    string s = "abacsddaa";
    int pos;
    int n = s.length(); 
    int query[] = {9, 3, 2};
    int Q = sizeof(query) / sizeof(query[0]);
    for(int i = 0; i < Q; i++ )
    
        pos = query[i] ;
        cout << Count( s, pos ) << endl;
    }
    return 0;
}
  
// This code is contributed by
// divyamohan123

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
class GFG 
{
    static int Count(String s, int pos )
    {
        // returns character at index pos - 1 
        int c = s.charAt(pos - 1);
        int counter = 0;
        for (int i = 0; i < pos - 1; i++ ) 
        {
            if(s.charAt(i) == c) 
                counter = counter + 1;
        }
        return counter;
    }
      
    // Driver Code 
    public static void main (String[] args)
    {
        String s = "abacsddaa";
        int pos;
        int n = s.length(); 
          
        int query[] = {9, 3, 2};
        int Q = query.length;
          
        for(int i = 0; i < Q; i++)
        
            pos = query[i];
            System.out.println(Count(s, pos));
        }
    }
}
  
// This code is contributed by AnkitRai01

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation of the approach
def Count( s, pos ):
    # returns character at index pos - 1
    c = s[pos - 1]
    counter = 0
    for i in range( pos - 1 ):
        if s[i] == c:
              counter = counter + 1  
    return counter
  
# Driver Code    
if __name__ == "__main__" :
    s = "abacsddaa"
    n = len(s)
    query = [9, 3, 2]
    Q = len(query)
    for i in range( Q ):
        pos = query[i]
        print(Count( s, pos ))

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
                      
class GFG 
{
    static int Count(String s, int pos )
    {
        // returns character at index pos - 1 
        int c = s[pos - 1];
        int counter = 0;
        for (int i = 0; i < pos - 1; i++ ) 
        {
            if(s[i] == c) 
                counter = counter + 1;
        }
        return counter;
    }
      
    // Driver Code 
    public static void Main (String[] args)
    {
        String s = "abacsddaa";
        int pos;
        int n = s.Length; 
          
        int []query = {9, 3, 2};
        int Q = query.Length;
          
        for(int i = 0; i < Q; i++)
        
            pos = query[i];
            Console.WriteLine(Count(s, pos));
        }
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

3
1
0

Time Complexity: O(N)
Space Complexity: O(1)

Better approach: Using Hashing or Dictionary and auxiliary space.
Create and auxiliary array say ‘temp’ which initialize to zero and hash table or dictionary ‘d’
initially empty. For pre-processing purpose, that is to store the previous count of element at index ‘pos’ at index pos in temp.

Preprocessing function
Pseudo Code:
function Preprocess(s):
      for i=1 to length(s),
           if s(i) not in hash_table,
                hash_table(s(i)) := i,
                end;
           else,
                auxiliary_array(i) = hash_table(s(i)) + 1,
                hash_table(s(i)) =  i,
                end;                

It place all the required value at respective index of auxiliary array. For each query Qi print val at position ‘pos’ in temp.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation of the approach
def Count( temp ):
    query = [9, 3, 2]
    Q = len(query)
    for i in range( Q ):
        pos = query[i]
        print( temp[pos-1] )
def processing( s ):
    temp = [ 0 ] * len( s )
    d = dict( )
    for i in range( len( s ) ):
        if s[i] not in d:
            d[ s[i] ] = i
        else:
            temp[i] = temp[ d[ s[i] ] ] + 1
            d[ s[i] ] = i
    return temp
      
# Driver Code    
if __name__ == "__main__" :
    s = "abacsddaa"
    n = len(s)
    temp = processing( s )
    Count( temp )

chevron_right


Output:

3
1
0

Time Complexity: O(N)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.