Like you can see here, I have this algorithm and I wanna know if the time complexity here is o(n) or o(n²).
public static boolean isTextPalindrome(String text) {
if (text == null) {
return false;
}
int left = 0;
int right = text.length() - 1;
while (left < right) {
if (text.charAt(left++) != text.charAt(right--)) {
return false;
}
}
return true;
}
In the worst case the complexity of this algorithm is O(n)
as it is directly dependend on the input but only linearly. In that case we can ignore the impact of the if condition as it has only constant impact on the complexity.
The best case would be if you input a word that starts with a letter that it does not end with. But as you cannot rely on that we are more interested in this worst case to have an upper limit of the complexity.
I would suggest as a rule of thumb: if you have a loop which depends on the input you have a O(n)
complexity. If there is another loop in the first one that is also dependend on the outer one the complexity increases to O(n^2)
. And so forth for more nested loops.