I have written a function and I need to know the big O notation for it.
I have tried to slove this myself and I get O(N^2), however I have been told that this is not the correct answer.
Can someone please tell me what the correct notation is and also a step by step explanation of how they came to that answer?
The function is below.
Thanks in advance
public static string Palindrome(string input)
{
string current = string.Empty;
string longest = string.Empty;
int left;
int center;
int right;
if (input == null || input == string.Empty || input.Length == 1) { return input; }
for (center = 1; center < input.Length -1; center++)
{
left = center - 1;
right = center + 1;
if (input[left] == input[center])
{
left--;
}
while (0 <= left && right < input.Length)
{
if (input[left] != input[right])
{
break;
}
current = input.Substring(left, (right - left + 1));
longest = current.Length > longest.Length ? current : longest;
left--;
right++;
}
}
return longest;
}
This is O(n^3) algorithm:
This part takes O(n^2):
Also there is an outer O(n),
forloop, which causes to O(n*n^2).You can improve your algorithm by changing this lines:
to:
and finally return a substring from longestLeft to longestRight. Actually avoid to use
substringmethod too many times.