Amazon Interview Question
Software Engineer / DevelopersThat makes it O(N^2). Better way would be to create a combined Suffix tree for S and reverse(S) and find the lowest internal node. This is only O(N).
If you mention and explain the suffix tree solution, I think you will make a very nice impression.
Can you please explain how will you find the largest palindrome using Suffix Tree. I didn't get you. explain it with the name "ALAM" here ALA is the longest palindrome. No need to code it. Just show me how the lowest internal node finds the solution.
suppose the original string is X
the reverse string is Y
find the largest common repetitive string of X#Y$ (suppose #,$ do not exist in X), that would be the result.
how to find the largest common repetitive string?
just check the suffix tree, find out the one that is not leaf (to make sure its count>=2)
and its length is the max.
for(int start=0;start<st.length;start++){
prev=start;next=start
while(prev>=0 && next<st.length && st[prev]==st[next])
prev--;next++
if(found string > Max)
//save string
if(start<st.length-1)
if(st[start]==st[start+1]){
prev=start-1;next=start+2
while(prev>=0 && next<st.length && st[prev]==st[next])
prev--;next++
if(found string > Max)
//save string
}
}
public class MaxPal {
public static void main(String[] args) {
String str = "woddooddaqowwoqad";
System.out.println(pal(str,0,str.length()-1));
}
private static int pal(String str, int lo, int hi) {
if(lo>=hi) return 0;
if(str.charAt(lo) == str.charAt(hi)) {
return pal(str,++lo,--hi) + 2;
}
return Math.max(pal(str,++lo,hi), pal(str,lo,--hi));
}
}
This is a exponential solution. memoizing this solution gives O(n^2) algo.. More efficient algos are possible..
O(nlogn) using hashing + binary Search
1. Make a copy of original string and reverse it.
- Tulley February 17, 20112. Find the longest common sub-sequence in both the string.