You are given a string ‘STR’. Your task is to return a prefix among all the prefixes of ‘STR’ that occurs the maximum number of times as a substring in ‘STR’. In case of a tie, return the longest prefix.
For example: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.
Output Format:
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
Note:
You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
2
ababcd
abcdaabcd
ab
a
For the first test case, 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”.
For the second test case, you are given ‘STR’ = “abcdaabcd”. Then our answer will be “a”. The prefix “a” occur the maximum number of times, i.e., 3.
2
abcdbcd
abcabcc
abcdbcd
abc
Find the count of every prefix.
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:
O(N ^ 3), where N is the length of the input string ‘STR’.
We are iterating through the ‘STR’ using three nested loops, and each loop makes at most N iterations. Hence, the overall time complexity will be O(N ^ 3).
O(N), where N is the length of the input string ‘STR’.
The extra space is used to store the current prefix, which can be as long as ‘STR’. Hence, the overall space complexity is O(N).