Maximum occurrence of prefix in the Array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of characters all in lowercase. Our task is to Maximum occurrence of prefix in the Array.

We need to count the occurrence of non-empty prefixes whose occurrence count is maximum.

Let’s take an example to understand the problem,

Input : string = “xyyzkxyyzk”
Output : 2

Solution Approach

The logic is to visualize that the prefix of an array must always, obviously, contain the first character of the string and so would be its repeating occurrences. And the first character of a string is obviously a prefix with the least number of characters. So the maximum occurring prefix would definitely be the first character of the string. So the job has now been reduced to find the count of the first character in the string.

Algorithm

• Read a string of lowercase alphabets.

• Create a function to return the count of the required prefix.

• Initialise count=0.

• Find the frequency of the first character of the string.

• Print the frequency of the first character of the string which would eventually be the maximum occurrence of a prefix of the string.

Example

Program to illustrate the working of our solution,

#include <iostream>
using namespace std;
int findPrefixOccurence(string str){
char chars = str[0];
int countOccrence = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == chars)
countOccrence++;
}
return countOccrence;
}
int main(){
string str = "xyyzxxyyzxyxx";
cout<<"The maximum occurence of prefix in the array is "<<findPrefixOccurence(str);
return 0;
}

Output

The maximum occurence of prefix in the array is 6
Updated on 24-Jan-2022 12:49:31