I was thinking of the following problem: Given a string S, let the length of the ith substring be li and number of occurrences of the ith substring be oi. Print the substring such that li*oi is maximized.
I have O(n3) solution (brute force) for this problem where I am generating all the substrings and finding the substring with maximum value. My code for the same is as follows:
public static void solve(String S) {
long max = Integer.MIN_VALUE;
String res = "";
for (int i = 0; i < S.length(); i++) {
for (int j = 1; j <= S.length() - i; j++) {
String s = S.substring(i, i + j);
int o = countOccurrences(S, s);
long p = (long) o * (long) s.length();
if (max < p) {
max = p;
res = s;
}
}
}
System.out.println(res);
}
where countOccurrences() method takes O(n) time. I was wondering if there was a more efficient way to achieve this.
Here's a linear-time algorithm:
The key points are that
It might also be possible to do this using suffix arrays instead of suffix trees, in which case it's likely to require a constant factor less memory, but add a logarithmic factor to the running time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With