Longest prefix in a string with highest frequency

Given a string, find a prefix with the highest frequency. If two prefixes have the same frequency then consider the one with maximum length.

Examples:

Input : str = "abc" 
Output : abc
Each prefix has same frequency(one) and the 
prefix with maximum length is "abc".

Input : str = "abcab"
Output : ab
Both prefix "a" and "ab" occur two times and the 
prefix with maximum length is "ab".

The idea is to observe that every prefix of the given string will contain the first character of the string in it and the first character alone is also a prefix of the given string. So the prefix with the highest occurrence is the first character. The task now remains to maximize the length of the highest frequency prefix.



Approach :

  1. Take a vector which will store the indices of the first element of the string.
  2. If the first element appeared only once, then the longest prefix will be the whole string.
  3. Otherwise, loop till the second appearance of the first element and check one letter after every stored index.
  4. If there is no mismatch we move forward otherwise we stop.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find Longest prefix string with the 
// highest frequency
void prefix(string str)
{
    int k = 1, j;
    int n = str.length();
  
    vector<int> g;
    int flag = 0;
  
    // storing all indices where first element is found
    for (int i = 1; i < n; i++) {
        if (str[i] == str[0]) {
            g.push_back(i);
            flag = 1;
        }
    }
  
    // if the first letter in the string does not occur 
    // again  then answer will be the whole string
    if (flag == 0) {
        cout << str << endl;
    }
    else {
        int len = g.size();
  
        // loop till second appearance of the first element
        while (k < g[0]) {
  
            int cnt = 0;
            for (j = 0; j < len; j++) {
  
                // check one letter after every stored index
                if (str[g[j] + k] == str[k]) {
                    cnt++;
                }
            }
  
            // If there is no mismatch we move forward
            if (cnt == len) {
                k++;
            }
            // otherwise we stop
            else {
                break;
            }
        }
  
        for (int i = 0; i < k; i++) {
            cout << str[i];
        }
  
        cout << endl;
    }
}
  
// Driver Code
int main()
{
    string str = "abcab";
    prefix(str);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the above approach
import java.util.*;
  
class GFG
{
  
    // Function to find Longest prefix string with the 
    // highest frequency
    static void prefix(char[] str) 
    {
        int k = 1, j;
        int n = str.length;
  
        Vector<Integer> g = new Vector<>();
        int flag = 0;
  
        // storing all indices where first element is found
        for (int i = 1; i < n; i++)
        {
            if (str[i] == str[0])
            {
                g.add(i);
                flag = 1;
            }
        }
  
        // if the first letter in the string does not occur 
        // again then answer will be the whole string
        if (flag == 0
        {
            System.out.println(String.valueOf(str));
        }
        else
        {
            int len = g.size();
  
            // loop till second appearance of the first element
            while (k < g.get(0)) 
            {
  
                int cnt = 0;
                for (j = 0; j < len; j++) 
                {
  
                    // check one letter after every stored index
                    if ((g.get(j) + k) < n && 
                        str[g.get(j) + k] == str[k])
                    {
                        cnt++;
                    }
                }
  
                // If there is no mismatch we move forward
                if (cnt == len)
                {
                    k++;
                
                // otherwise we stop
                else 
                {
                    break;
                }
            }
  
            for (int i = 0; i < k; i++) 
            {
                System.out.print(str[i]);
            }
  
            System.out.println();
        }
    }
  
    // Driver Code
    public static void main(String args[])
    {
        String str = "abcab";
        prefix(str.toCharArray());
    }
}
  
/* This code contributed by PrinciRaj1992 */

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the above approach 
  
# Function to find Longest prefix string with the 
# highest frequency 
def prefix(string) :
  
    k = 1
    n = len(string); 
  
    g = []; 
    flag = 0
  
    # storing all indices where first element is found 
    for i in range(1, n) :
        if (string[i] == string[0]) :
            g.append(i); 
            flag = 1
  
    # if the first letter in the string does not occur 
    # again then answer will be the whole string 
    if (flag == 0) :
        print(string); 
       
    else :
        length = len(g);
          
        # loop till second appearance of the first element
        while (k < g[0]) :
            cnt = 0;
              
            for j in range(length) :
                  
                # check one letter after every stored index
                if (string[g[j] + k] == string[k]) :
                    cnt += 1;
                      
            # If there is no mismatch we move forward
            if (cnt == len) :
                k += 1;
             
            # otherwise we stop
            else :
                break;
         
        for i in range(k+1) :
            print(string[i],end="");
         
        print() 
  
# Driver Code 
if __name__ == "__main__"
  
    string = "abcab"
    prefix(string); 
  
# This code is contributed by AnkitRai01

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the above approach
using System;
using System.Collections.Generic; 
  
class GFG
{
  
    // Function to find Longest prefix string with the 
    // highest frequency
    static void prefix(char[] str) 
    {
        int k = 1, j;
        int n = str.Length;
  
        List<int> g = new List<int>();
        int flag = 0;
  
        // storing all indices where first element is found
        for (int i = 1; i < n; i++)
        {
            if (str[i] == str[0])
            {
                g.Add(i);
                flag = 1;
            }
        }
  
        // if the first letter in the string does not occur 
        // again then answer will be the whole string
        if (flag == 0) 
        {
            Console.WriteLine(String.Join("",str));
        }
        else
        {
            int len = g.Count;
  
            // loop till second appearance of the first element
            while (k < g[0]) 
            {
  
                int cnt = 0;
                for (j = 0; j < len; j++) 
                {
  
                    // check one letter after every stored index
                    if ((g[j] + k) < n && 
                        str[g[j] + k] == str[k])
                    {
                        cnt++;
                    }
                }
  
                // If there is no mismatch we move forward
                if (cnt == len)
                {
                    k++;
                
                // otherwise we stop
                else
                {
                    break;
                }
            }
  
            for (int i = 0; i < k; i++) 
            {
                Console.Write(str[i]);
            }
  
            Console.WriteLine();
        }
    }
  
    // Driver Code
    public static void Main()
    {
        String str = "abcab";
        prefix(str.ToCharArray());
    }
}
  
// This code contributed by Rajput-Ji

chevron_right


Output:

ab

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.