Maximum occurrence of prefix in the Array
Last Updated :
02 Sep, 2022
Given a string consisting of lower case English Alphabets. The task is to count the number of occurrences of the non-empty prefix which occurs the maximum number of times in the string as a substring.
Examples:
Input : str = “abbcdabbcd”
Output : 2
Explanation: The prefix “abb” has maximum number of occurrences 2.
Input : str = “abc”
Output : 1
Approach: The idea is to observe that every prefix of the array must contain the first character of the string and each of its respective occurrences will also. Also, the 1st character of a string is the minimum length prefix. So, the prefix with maximum number of occurrences will be the first character of the string itself. Therefore, the task now reduces to find the frequency of the first character in the given string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int prefixOccurrences(string str)
{
char c = str[0];
int countc = 0;
for ( int i = 0; i < str.length(); i++) {
if (str[i] == c)
countc++;
}
return countc;
}
int main()
{
string str = "abbcdabbcd" ;
cout << prefixOccurrences(str);
return 0;
}
|
Java
class GFG
{
static int prefixOccurrences(String str)
{
char c = str.charAt( 0 );
int countc = 0 ;
for ( int i = 0 ; i < str.length(); i++)
{
if (str.charAt(i) == c)
countc++;
}
return countc;
}
public static void main(String args[])
{
String str = "abbcdabbcd" ;
System.out.println(prefixOccurrences(str));
}
}
|
Python3
def prefixOccurrences(str1):
c = str1[ 0 ]
countc = 0
for i in range ( len (str1)):
if (str1[i] = = c):
countc + = 1
return countc
str1 = "abbcdabbcd"
print (prefixOccurrences(str1))
|
C#
using System;
class GFG
{
static int prefixOccurrences( string str)
{
char c = str[0];
int countc = 0;
for ( int i = 0; i < str.Length; i++)
{
if (str[i] == c)
countc++;
}
return countc;
}
public static void Main()
{
string str = "abbcdabbcd" ;
Console.WriteLine(prefixOccurrences(str));
}
}
|
Javascript
<script>
function prefixOccurrences(str)
{
var c = str.charAt(0);
var countc = 0;
for ( var i = 0; i < str.length; i++)
{
if (str.charAt(i) == c)
countc++;
}
return countc;
}
var str = "abbcdabbcd" ;
document.write(prefixOccurrences(str));
</script>
|
Time complexity: O(N), where N is the length of the given string
Auxiliary space: O(1) as constant space is being used.
Share your thoughts in the comments
Please Login to comment...