


You are given ‘STR’ = “ababcd”. Then our answer will be “ab”. The prefixes “a” and “ab” occur the maximum number of times, i.e., 2. As the prefix “ab” is longer than “a” so, our answer will be “ab”.
The first line contains an integer 'T' which denotes the number of test cases.
The first line of each test case contains a string denoting the input string.
For each test case, print the prefix among all the prefixes of ‘STR’ that occurs the maximum number of times as a substring in ‘STR’.
The output of each test case will be printed in a separate line.
1 <= T <= 10
1 <= STR.LENGTH <= 5000
‘STR’ contains only lowercase English letters.
Time limit: 1 sec
You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
In this approach, we will find the count of the occurrences of every prefix starting with the smallest one and store it in a variable ‘COUNT’. We will also use the variable ‘MAXCOUNT’ to store the maximum number of times a prefix has occurred. If the current ‘COUNT’ is greater than or equal to ‘MAXCOUNT’, then we will update our answer accordingly.
Algorithm:
We know that prefix is the leading contiguous part of a string. A prefix always starts from the first character of the string. Hence, we can say that the first character alone is the prefix that occurs maximum times in the string because all the string prefixes will contain the first character. But a prefix may exist that occurs as many times as the first character and has a greater length. In that case, the longer prefix will be our answer.
For example, if the given ‘STR’ is ‘ababcd’, the prefixes “a” and “ab” occur the maximum number of times, i.e., 2. But our answer is “ab” because “ab” is longer than “a”.
If the length of our answer is K, then all the occurrences of the first character must be followed immediately by the same K - 1 characters. So, to find the longest prefix that occurs the maximum number of times, we will maintain a list of occurrences of the first character and check the following characters, moving forward from every occurrence of the first character until any mismatch happens. Suppose if the mismatch happens at position ‘POS’, then the substring ‘STR[0:’POS’ - 1] will be our answer.
Algorithm: