Count of substrings having the most frequent character in the string as first character
Last Updated :
28 Dec, 2022
Given a string S consisting of lowercase alphabets of size N, the task is to count all substrings which contain the most frequent character in the string as the first character.
Note: If more than one character has a maximum frequency, consider the lexicographically smallest among them.
Examples:
Input: S = "abcab"
Output: 7
Explanation:
There are two characters a and b occurring maximum times i.e., 2 times.
Selecting the lexicographically smaller character i.e. 'a'.
Substrings starts with 'a' are: "a", "ab", "abc", "abca", "abcab", "a", "ab".
Therefore the count is 7.
Input: S= "cccc"
Output: 10
Approach: The idea is to first find the character that occurs the maximum number of times and then count the substring starting with that character in the string. Follow the steps below to solve the problem:
- Initialize the count as 0 that will store the total count of strings.
- Find the maximum occurring character in the string S. Let that character be ch.
- Traverse the string using the variable i and if the character at ith index is the same as ch, increment the count by (N - i).
- After the above steps, print the value of count as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include<bits/stdc++.h>
using namespace std;
// Function to find all substrings
// whose first character occurs
// maximum number of times
int substringCount(string s)
{
// Stores frequency of characters
vector<int> freq(26, 0);
// Stores character that appears
// maximum number of times
char max_char = '#';
// Stores max frequency of character
int maxfreq = INT_MIN;
// Updates frequency of characters
for(int i = 0; i < s.size(); i++)
{
freq[s[i] - 'a']++;
// Update maxfreq
if (maxfreq < freq[s[i] - 'a'])
maxfreq = freq[s[i] - 'a'];
}
// Character that occurs
// maximum number of times
for(int i = 0; i < 26; i++)
{
// Update the maximum frequency
// character
if (maxfreq == freq[i])
{
max_char = (char)(i + 'a');
break;
}
}
// Stores all count of substrings
int ans = 0;
// Traverse over string
for(int i = 0; i < s.size(); i++)
{
// Get the current character
char ch = s[i];
// Update count of substrings
if (max_char == ch)
{
ans += (s.size() - i);
}
}
// Return the count of all
// valid substrings
return ans;
}
// Driver Code
int main()
{
string S = "abcab";
// Function Call
cout << (substringCount(S));
}
// This code is contributed by mohit kumar 29
Java
// Java program for the above approach
import java.util.*;
class GFG {
// Function to find all substrings
// whose first character occurs
// maximum number of times
static int substringCount(String s)
{
// Stores frequency of characters
int[] freq = new int[26];
// Stores character that appears
// maximum number of times
char max_char = '#';
// Stores max frequency of character
int maxfreq = Integer.MIN_VALUE;
// Updates frequency of characters
for (int i = 0;
i < s.length(); i++) {
freq[s.charAt(i) - 'a']++;
// Update maxfreq
if (maxfreq
< freq[s.charAt(i) - 'a'])
maxfreq
= freq[s.charAt(i) - 'a'];
}
// Character that occurs
// maximum number of times
for (int i = 0; i < 26; i++) {
// Update the maximum frequency
// character
if (maxfreq == freq[i]) {
max_char = (char)(i + 'a');
break;
}
}
// Stores all count of substrings
int ans = 0;
// Traverse over string
for (int i = 0;
i < s.length(); i++) {
// Get the current character
char ch = s.charAt(i);
// Update count of substrings
if (max_char == ch) {
ans += (s.length() - i);
}
}
// Return the count of all
// valid substrings
return ans;
}
// Driver Code
public static void main(String[] args)
{
String S = "abcab";
// Function Call
System.out.println(substringCount(S));
}
}
Python3
# Python3 program for the above approach
import sys
# Function to find all substrings
# whose first character occurs
# maximum number of times
def substringCount(s):
# Stores frequency of characters
freq = [0 for i in range(26)]
# Stores character that appears
# maximum number of times
max_char = '#'
# Stores max frequency of character
maxfreq = -sys.maxsize - 1
# Updates frequency of characters
for i in range(len(s)):
freq[ord(s[i]) - ord('a')] += 1
# Update maxfreq
if (maxfreq < freq[ord(s[i]) - ord('a')]):
maxfreq = freq[ord(s[i]) - ord('a')]
# Character that occurs
# maximum number of times
for i in range(26):
# Update the maximum frequency
# character
if (maxfreq == freq[i]):
max_char = chr(i + ord('a'))
break
# Stores all count of substrings
ans = 0
# Traverse over string
for i in range(len(s)):
# Get the current character
ch = s[i]
# Update count of substrings
if (max_char == ch):
ans += (len(s) - i)
# Return the count of all
# valid substrings
return ans
# Driver Code
if __name__ == '__main__':
S = "abcab"
# Function Call
print(substringCount(S))
# This code is contributed by ipg2016107
C#
// C# program for the above approach
using System;
class GFG{
// Function to find all substrings
// whose first character occurs
// maximum number of times
static int substringCount(string s)
{
// Stores frequency of characters
int[] freq = new int[26];
// Stores character that appears
// maximum number of times
char max_char = '#';
// Stores max frequency of character
int maxfreq = Int32.MinValue;
// Updates frequency of characters
for(int i = 0; i < s.Length; i++)
{
freq[s[i] - 'a']++;
// Update maxfreq
if (maxfreq < freq[s[i] - 'a'])
maxfreq = freq[s[i] - 'a'];
}
// Character that occurs
// maximum number of times
for(int i = 0; i < 26; i++)
{
// Update the maximum frequency
// character
if (maxfreq == freq[i])
{
max_char = (char)(i + 'a');
break;
}
}
// Stores all count of substrings
int ans = 0;
// Traverse over string
for(int i = 0; i < s.Length; i++)
{
// Get the current character
char ch = s[i];
// Update count of substrings
if (max_char == ch)
{
ans += (s.Length - i);
}
}
// Return the count of all
// valid substrings
return ans;
}
// Driver Code
public static void Main()
{
string S = "abcab";
// Function Call
Console.WriteLine(substringCount(S));
}
}
// This code is contributed by susmitakundugoaldanga
JavaScript
<script>
// JavaScript program for the above approach
// Function to find all substrings
// whose first character occurs
// maximum number of times
function substringCount(s)
{
// Stores frequency of characters
var freq = new Array(26).fill(0);
// Stores character that appears
// maximum number of times
var max_char = "#";
// Stores max frequency of character
var maxfreq = -21474836487;
// Updates frequency of characters
for(var i = 0; i < s.length; i++)
{
freq[s[i].charCodeAt(0) -
"a".charCodeAt(0)]++;
// Update maxfreq
if (maxfreq < freq[s[i].charCodeAt(0) -
"a".charCodeAt(0)])
maxfreq = freq[s[i].charCodeAt(0) -
"a".charCodeAt(0)];
}
// Character that occurs
// maximum number of times
for(var i = 0; i < 26; i++)
{
// Update the maximum frequency
// character
if (maxfreq === freq[i])
{
max_char = String.fromCharCode(
i + "a".charCodeAt(0));
break;
}
}
// Stores all count of substrings
var ans = 0;
// Traverse over string
for(var i = 0; i < s.length; i++)
{
// Get the current character
var ch = s[i];
// Update count of substrings
if (max_char === ch)
{
ans += s.length - i;
}
}
// Return the count of all
// valid substrings
return ans;
}
// Driver Code
var S = "abcab";
// Function Call
document.write(substringCount(S));
// This code is contributed by rdtank
</script>
Time Complexity: O(N), as we are using a loop to traverse the string.
Auxiliary Space: O(1), as we are using freq array of size 26 which is constant.
Similar Reads
Count substrings having frequency of a character exceeding that of another character in a string Given a string S of size N consisting of characters a, b, and c only, the task is to find the number of substrings of the given string S such that the frequency of character a is greater than the frequency of character c. Examples: Input: S = "abcc"Output: 2Explanation:Below are all the possible sub
15 min read
Count of substrings with the frequency of at most one character as Odd Given a string S of N characters, the task is to calculate the total number of non-empty substrings such that at most one character occurs an odd number of times. Example: Input: S = "aba"Output: 4Explanation: The valid substrings are "a", "b", "a", and "aba". Therefore, the total number of required
7 min read
Count of substrings of given string with frequency of each character at most K Given a string str, the task is to calculate the number of substrings of the given string such that the frequency of each element of the string is almost K. Examples: Input: str = "abab", K = 1Output: 7Explanation: The substrings such that the frequency of each character is atmost 1 are "a", "b", "a
6 min read
Count of Substrings with at least K pairwise Distinct Characters having same Frequency Given a string S and an integer K, the task is to find the number of substrings which consists of at least K pairwise distinct characters having same frequency. Examples: Input: S = "abasa", K = 2 Output: 5 Explanation: The substrings in having 2 pairwise distinct characters with same frequency are
7 min read
Find frequency of all characters across all substrings of given string Given a string S containing all lowercase characters and its length N. Find frequency of all characters across all substrings of the given string. Examples: Input: N = 3, S = "aba"Output: a 6b 4Explanation: The substrings are: a, b, a, ab, ba, aba. The frequency of each character: a = 6, b = 4. Henc
4 min read
Count substrings with each character occurring at most k times Given a string S. Count number of substrings in which each character occurs at most k times. Assume that the string consists of only lowercase English alphabets. Examples: Input : S = ab k = 1 Output : 3 All the substrings a, b, ab have individual character count less than 1. Input : S = aaabb k = 2
15+ min read