Most Frequent Alphabet

Most Frequent Alphabet - CTS GenCNext 

The program must accept a string S containing only lower case alphabets and Q queries as the input. Each query contains two integers representing the starting and the ending indices of a substring in S. For each query, the program must print the most frequently occurring alphabet in the specified substring. If two or more alphabets have the same frequency, then the program must print the alphabet that is least in the alphabetical order. 

Boundary Condition(s): 

2 <= Length of S <= 1000 

1 <= Q <= 10^5 

Input Format: 

The first line contains S. The second line contains Q. The next Q lines, each containing two integers representing the starting and the ending indices of a substring in S. 

Output Format: 

The first Q lines, each containing the most frequently occurring alphabet in the specified substring. 

Example Input/Output 1: 

Input: 

badbadbed 

0 8 

1 4 

0 5 

2 7

Output: 

Explanation: 

Here the given string S is badbadbed and the number of queries Q is 4. For 1st query, the substring is badbadbed. The alphabets b and d occur the same maximum number of times (3 times). So the alphabet that is least in the alphabetical order b is printed. For 2nd query, the substring is adba. The alphabet a occurs the maximum number of times (2 times). So a is printed. For 3rd query, the substring is badbad. The alphabets b, a and d occur the same maximum number of times (2 times). So the alphabet that is least in the alphabetical order a is printed. For 4th query, the substring is dbadbe. The alphabets d and b occur the same maximum number of times (2 times). So the alphabet that is least in the alphabetical order b is printed. Hence the output is b a a b 

Example Input/Output 2: 

Input: 

comeonmonsoon 

1 6 

4 8 

8 12 

5 10 

1 12 

2 5 

7 9 

Output: 

n

Program:

s = input().strip()

q = int(input())

for i in range(q):

    a,b = map(int,input().split())

    maxfreq = 0 

    maxchar = ""

    for j in set(s[a:b+1]):

        freq = s[a:b+1].count(j) 

        if freq > maxfreq:

            maxfreq = freq 

            maxchar = j 

        elif freq == maxfreq:

            maxchar = chr(min(ord(j),ord(maxchar)))

    print(maxchar)        

Comments

Popular posts from this blog

Pronic Integers in N - InfyTQ question

Count Strong Points - Accenture

Letters at position of multiples of a number